]> git.lyx.org Git - lyx.git/blob - src/Paragraph.cpp
remove superfluous semicolons at the end of namespaces
[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 Richard Heck (XHTML output)
9  * \author Jean-Marc Lasgouttes
10  * \author Angus Leeming
11  * \author John Levon
12  * \author André Pönitz
13  * \author Dekel Tsur
14  * \author Jürgen Vigna
15  *
16  * Full author contact details are available in file CREDITS.
17  */
18
19 #include <config.h>
20
21 #include "Paragraph.h"
22
23 #include "LayoutFile.h"
24 #include "Buffer.h"
25 #include "BufferParams.h"
26 #include "Changes.h"
27 #include "Counters.h"
28 #include "Encoding.h"
29 #include "InsetList.h"
30 #include "Language.h"
31 #include "LaTeXFeatures.h"
32 #include "Layout.h"
33 #include "Length.h"
34 #include "Font.h"
35 #include "FontList.h"
36 #include "LyXRC.h"
37 #include "OutputParams.h"
38 #include "output_latex.h"
39 #include "output_xhtml.h"
40 #include "ParagraphParameters.h"
41 #include "SpellChecker.h"
42 #include "sgml.h"
43 #include "TextClass.h"
44 #include "TexRow.h"
45 #include "Text.h"
46 #include "VSpace.h"
47 #include "WordLangTuple.h"
48 #include "WordList.h"
49
50 #include "frontends/alert.h"
51
52 #include "insets/InsetBibitem.h"
53 #include "insets/InsetLabel.h"
54 #include "insets/InsetSpecialChar.h"
55
56 #include "support/debug.h"
57 #include "support/docstring_list.h"
58 #include "support/ExceptionMessage.h"
59 #include "support/gettext.h"
60 #include "support/lassert.h"
61 #include "support/lstrings.h"
62 #include "support/textutils.h"
63
64 #include <sstream>
65 #include <vector>
66
67 using namespace std;
68 using namespace lyx::support;
69
70 namespace lyx {
71
72 namespace {
73 /// Inset identifier (above 0x10ffff, for ucs-4)
74 char_type const META_INSET = 0x200001;
75 }
76
77
78 /////////////////////////////////////////////////////////////////////
79 //
80 // SpellResultRange
81 //
82 /////////////////////////////////////////////////////////////////////
83
84 class SpellResultRange {
85 public:
86         SpellResultRange(FontSpan range, SpellChecker::Result result)
87         : range_(range), result_(result)
88         {}
89         ///
90         FontSpan const & range() const { return range_; }
91         ///
92         void range(FontSpan const & r) { range_ = r; }
93         ///
94         SpellChecker::Result result() const { return result_; }
95         ///
96         void result(SpellChecker::Result r) { result_ = r; }
97         ///
98         bool inside(pos_type pos) const { return range_.inside(pos); }
99         ///
100         bool covered(FontSpan const & r) const
101         {
102                 // 1. first of new range inside current range or
103                 // 2. last of new range inside current range or
104                 // 3. first of current range inside new range or
105                 // 4. last of current range inside new range
106                 return range_.inside(r.first) || range_.inside(r.last) ||
107                         r.inside(range_.first) || r.inside(range_.last);
108         }
109         ///
110         void shift(pos_type pos, int offset)
111         {
112                 if (range_.first > pos) {
113                         range_.first += offset;
114                         range_.last += offset;
115                 } else if (range_.last > pos) {
116                         range_.last += offset;
117                 }
118         }
119 private:
120         FontSpan range_ ;
121         SpellChecker::Result result_ ;
122 };
123
124
125 /////////////////////////////////////////////////////////////////////
126 //
127 // SpellCheckerState
128 //
129 /////////////////////////////////////////////////////////////////////
130
131 class SpellCheckerState {
132 public:
133         SpellCheckerState() {
134                 needs_refresh_ = true;
135                 current_change_number_ = 0;
136         }
137
138         void setRange(FontSpan const fp, SpellChecker::Result state)
139         {
140                 eraseCoveredRanges(fp);
141                 if (state != SpellChecker::WORD_OK)
142                         ranges_.push_back(SpellResultRange(fp, state));
143         }
144
145         void increasePosAfterPos(pos_type pos)
146         {
147                 correctRangesAfterPos(pos, 1);
148                 needsRefresh(pos);
149         }
150
151         void decreasePosAfterPos(pos_type pos)
152         {
153                 correctRangesAfterPos(pos, -1);
154                 needsRefresh(pos);
155         }
156
157         void refreshLast(pos_type pos)
158         {
159                 if (pos < refresh_.last)
160                         refresh_.last = pos;
161         }
162
163         SpellChecker::Result getState(pos_type pos) const
164         {
165                 SpellChecker::Result result = SpellChecker::WORD_OK;
166                 RangesIterator et = ranges_.end();
167                 RangesIterator it = ranges_.begin();
168                 for (; it != et; ++it) {
169                         if(it->inside(pos)) {
170                                 return it->result();
171                         }
172                 }
173                 return result;
174         }
175
176         bool needsRefresh() const {
177                 return needs_refresh_;
178         }
179
180         SpellChecker::ChangeNumber currentChangeNumber() const {
181                 return current_change_number_;
182         }
183
184         void refreshRange(pos_type & first, pos_type & last) const {
185                 first = refresh_.first;
186                 last = refresh_.last;
187         }
188
189         void needsRefresh(pos_type pos) {
190                 if (needs_refresh_ && pos != -1) {
191                         if (pos < refresh_.first)
192                                 refresh_.first = pos;
193                         if (pos > refresh_.last)
194                                 refresh_.last = pos;
195                 } else if (pos != -1) {
196                         refresh_.first = pos;
197                         refresh_.last = pos;
198                 }
199                 needs_refresh_ = pos != -1;
200         }
201
202         void needsCompleteRefresh(SpellChecker::ChangeNumber change_number) {
203                 needs_refresh_ = true;
204                 refresh_.first = 0;
205                 refresh_.last = -1;
206                 current_change_number_ = change_number;
207         }
208
209 private:
210         typedef vector<SpellResultRange> Ranges;
211         typedef Ranges::const_iterator RangesIterator;
212         Ranges ranges_;
213         /// the area of the paragraph with pending spell check
214         FontSpan refresh_;
215         bool needs_refresh_;
216         /// spell state cache version number
217         SpellChecker::ChangeNumber current_change_number_;
218
219
220         void eraseCoveredRanges(FontSpan const fp)
221         {
222                 Ranges result;
223                 RangesIterator et = ranges_.end();
224                 RangesIterator it = ranges_.begin();
225                 for (; it != et; ++it) {
226                         if (!it->covered(fp))
227                                 result.push_back(SpellResultRange(it->range(), it->result()));
228                 }
229                 ranges_ = result;
230         }
231
232         void correctRangesAfterPos(pos_type pos, int offset)
233         {
234                 RangesIterator et = ranges_.end();
235                 Ranges::iterator it = ranges_.begin();
236                 for (; it != et; ++it) {
237                         it->shift(pos, offset);
238                 }
239         }
240
241 };
242
243 /////////////////////////////////////////////////////////////////////
244 //
245 // Paragraph::Private
246 //
247 /////////////////////////////////////////////////////////////////////
248
249 class Paragraph::Private
250 {
251 public:
252         ///
253         Private(Paragraph * owner, Layout const & layout);
254         /// "Copy constructor"
255         Private(Private const &, Paragraph * owner);
256         /// Copy constructor from \p beg  to \p end
257         Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
258
259         ///
260         void insertChar(pos_type pos, char_type c, Change const & change);
261
262         /// Output the surrogate pair formed by \p c and \p next to \p os.
263         /// \return the number of characters written.
264         int latexSurrogatePair(odocstream & os, char_type c, char_type next,
265                                OutputParams const &);
266
267         /// Output a space in appropriate formatting (or a surrogate pair
268         /// if the next character is a combining character).
269         /// \return whether a surrogate pair was output.
270         bool simpleTeXBlanks(OutputParams const &,
271                              odocstream &, TexRow & texrow,
272                              pos_type i,
273                              unsigned int & column,
274                              Font const & font,
275                              Layout const & style);
276
277         /// Output consecutive unicode chars, belonging to the same script as
278         /// specified by the latex macro \p ltx, to \p os starting from \p i.
279         /// \return the number of characters written.
280         int writeScriptChars(odocstream & os, docstring const & ltx,
281                            Change const &, Encoding const &, pos_type & i);
282
283         /// This could go to ParagraphParameters if we want to.
284         int startTeXParParams(BufferParams const &, odocstream &, TexRow &,
285                               OutputParams const &) const;
286
287         /// This could go to ParagraphParameters if we want to.
288         int endTeXParParams(BufferParams const &, odocstream &, TexRow &,
289                             OutputParams const &) const;
290
291         ///
292         void latexInset(BufferParams const &,
293                                    odocstream &,
294                                    TexRow & texrow, OutputParams &,
295                                    Font & running_font,
296                                    Font & basefont,
297                                    Font const & outerfont,
298                                    bool & open_font,
299                                    Change & running_change,
300                                    Layout const & style,
301                                    pos_type & i,
302                                    unsigned int & column);
303
304         ///
305         void latexSpecialChar(
306                                    odocstream & os,
307                                    OutputParams const & runparams,
308                                    Font const & running_font,
309                                    Change const & running_change,
310                                    Layout const & style,
311                                    pos_type & i,
312                                    unsigned int & column);
313
314         ///
315         bool latexSpecialT1(
316                 char_type const c,
317                 odocstream & os,
318                 pos_type i,
319                 unsigned int & column);
320         ///
321         bool latexSpecialTypewriter(
322                 char_type const c,
323                 odocstream & os,
324                 pos_type i,
325                 unsigned int & column);
326         ///
327         bool latexSpecialPhrase(
328                 odocstream & os,
329                 pos_type & i,
330                 unsigned int & column,
331                 OutputParams const & runparams);
332
333         ///
334         void validate(LaTeXFeatures & features) const;
335
336         /// Checks if the paragraph contains only text and no inset or font change.
337         bool onlyText(Buffer const & buf, Font const & outerfont,
338                       pos_type initial) const;
339
340         /// match a string against a particular point in the paragraph
341         bool isTextAt(string const & str, pos_type pos) const;
342
343         /// a vector of speller skip positions
344         typedef vector<FontSpan> SkipPositions;
345         typedef SkipPositions::const_iterator SkipPositionsIterator;
346
347         void appendSkipPosition(SkipPositions & skips, pos_type const pos) const;
348         
349         Language * getSpellLanguage(pos_type const from) const;
350
351         Language * locateSpellRange(pos_type & from, pos_type & to,
352                                                                 SkipPositions & skips) const;
353
354         bool hasSpellerChange() const {
355                 SpellChecker::ChangeNumber speller_change_number = 0;
356                 if (theSpellChecker())
357                         speller_change_number = theSpellChecker()->changeNumber();
358                 return speller_change_number > speller_state_.currentChangeNumber();
359         }
360
361         bool ignoreWord(docstring const & word) const ;
362         
363         void setMisspelled(pos_type from, pos_type to, SpellChecker::Result state)
364         {
365                 pos_type textsize = owner_->size();
366                 // check for sane arguments
367                 if (to < from || from >= textsize)
368                         return;
369                 FontSpan fp = FontSpan(from, to);
370                 // don't mark end of paragraph
371                 if (fp.last >= textsize)
372                         fp.last = textsize - 1;
373                 speller_state_.setRange(fp, state);
374         }
375
376         void requestSpellCheck(pos_type pos) {
377                 speller_state_.needsRefresh(pos);
378         }
379
380         void readySpellCheck() {
381                 speller_state_.needsRefresh(-1);
382         }
383
384         bool needsSpellCheck() const
385         {
386                 return speller_state_.needsRefresh();
387         }
388
389         void rangeOfSpellCheck(pos_type & first, pos_type & last) const
390         {
391                 speller_state_.refreshRange(first, last);
392                 if (last == -1) {
393                         last = owner_->size();
394                         return;
395                 }
396                 pos_type endpos = last;
397                 owner_->locateWord(first, endpos, WHOLE_WORD);
398                 if (endpos < last) {
399                         endpos = last;
400                         owner_->locateWord(last, endpos, WHOLE_WORD);
401                 }
402                 last = endpos;
403         }
404
405         int countSkips(SkipPositionsIterator & it, SkipPositionsIterator const et,
406                             int & start) const
407         {
408                 int numskips = 0;
409                 while (it != et && it->first < start) {
410                         int skip = it->last - it->first + 1;
411                         start += skip;
412                         numskips += skip;
413                         ++it;
414                 }
415                 return numskips;
416         }
417
418         void markMisspelledWords(pos_type const & first, pos_type const & last,
419                                                          SpellChecker::Result result,
420                                                          docstring const & word,
421                                                          SkipPositions const & skips);
422
423         InsetCode ownerCode() const
424         {
425                 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
426         }
427
428         /// Which Paragraph owns us?
429         Paragraph * owner_;
430
431         /// In which Inset?
432         Inset const * inset_owner_;
433
434         ///
435         FontList fontlist_;
436
437         ///
438         int id_;
439
440         ///
441         ParagraphParameters params_;
442
443         /// for recording and looking up changes
444         Changes changes_;
445
446         ///
447         InsetList insetlist_;
448
449         /// end of label
450         pos_type begin_of_body_;
451
452         typedef docstring TextContainer;
453         ///
454         TextContainer text_;
455
456         typedef set<docstring> Words;
457         typedef map<Language, Words> LangWordsMap;
458         ///
459         LangWordsMap words_;
460         ///
461         Layout const * layout_;
462         ///
463         SpellCheckerState speller_state_;
464 };
465
466
467 namespace {
468
469 struct special_phrase {
470         string phrase;
471         docstring macro;
472         bool builtin;
473 };
474
475 special_phrase const special_phrases[] = {
476         { "LyX", from_ascii("\\LyX{}"), false },
477         { "TeX", from_ascii("\\TeX{}"), true },
478         { "LaTeX2e", from_ascii("\\LaTeXe{}"), true },
479         { "LaTeX", from_ascii("\\LaTeX{}"), true },
480 };
481
482 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
483
484 } // namespace anon
485
486
487 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
488         : owner_(owner), inset_owner_(0), id_(-1), begin_of_body_(0), layout_(&layout)
489 {
490         text_.reserve(100);
491 }
492
493
494 // Initialization of the counter for the paragraph id's,
495 //
496 // FIXME: There should be a more intelligent way to generate and use the
497 // paragraph ids per buffer instead a global static counter for all InsetText
498 // in the running program.
499 static int paragraph_id = -1;
500
501 Paragraph::Private::Private(Private const & p, Paragraph * owner)
502         : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
503           params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
504           begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
505           layout_(p.layout_)
506 {
507         id_ = ++paragraph_id;
508         requestSpellCheck(p.text_.size());
509 }
510
511
512 Paragraph::Private::Private(Private const & p, Paragraph * owner,
513         pos_type beg, pos_type end)
514         : owner_(owner), inset_owner_(p.inset_owner_),
515           params_(p.params_), changes_(p.changes_),
516           insetlist_(p.insetlist_, beg, end),
517           begin_of_body_(p.begin_of_body_), words_(p.words_),
518           layout_(p.layout_)
519 {
520         id_ = ++paragraph_id;
521         if (beg >= pos_type(p.text_.size()))
522                 return;
523         text_ = p.text_.substr(beg, end - beg);
524
525         FontList::const_iterator fcit = fontlist_.begin();
526         FontList::const_iterator fend = fontlist_.end();
527         for (; fcit != fend; ++fcit) {
528                 if (fcit->pos() < beg)
529                         continue;
530                 if (fcit->pos() >= end) {
531                         // Add last entry in the fontlist_.
532                         fontlist_.set(text_.size() - 1, fcit->font());
533                         break;
534                 }
535                 // Add a new entry in the fontlist_.
536                 fontlist_.set(fcit->pos() - beg, fcit->font());
537         }
538         requestSpellCheck(p.text_.size());
539 }
540
541
542 void Paragraph::addChangesToToc(DocIterator const & cdit,
543         Buffer const & buf) const
544 {
545         d->changes_.addToToc(cdit, buf);
546 }
547
548
549 bool Paragraph::isDeleted(pos_type start, pos_type end) const
550 {
551         LASSERT(start >= 0 && start <= size(), /**/);
552         LASSERT(end > start && end <= size() + 1, /**/);
553
554         return d->changes_.isDeleted(start, end);
555 }
556
557
558 bool Paragraph::isChanged(pos_type start, pos_type end) const
559 {
560         LASSERT(start >= 0 && start <= size(), /**/);
561         LASSERT(end > start && end <= size() + 1, /**/);
562
563         return d->changes_.isChanged(start, end);
564 }
565
566
567 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
568 {
569         // keep the logic here in sync with the logic of eraseChars()
570         if (!trackChanges)
571                 return true;
572
573         Change const change = d->changes_.lookup(size());
574         return change.inserted() && change.currentAuthor();
575 }
576
577
578 void Paragraph::setChange(Change const & change)
579 {
580         // beware of the imaginary end-of-par character!
581         d->changes_.set(change, 0, size() + 1);
582
583         /*
584          * Propagate the change recursively - but not in case of DELETED!
585          *
586          * Imagine that your co-author makes changes in an existing inset. He
587          * sends your document to you and you come to the conclusion that the
588          * inset should go completely. If you erase it, LyX must not delete all
589          * text within the inset. Otherwise, the change tracked insertions of
590          * your co-author get lost and there is no way to restore them later.
591          *
592          * Conclusion: An inset's content should remain untouched if you delete it
593          */
594
595         if (!change.deleted()) {
596                 for (pos_type pos = 0; pos < size(); ++pos) {
597                         if (Inset * inset = getInset(pos))
598                                 inset->setChange(change);
599                 }
600         }
601 }
602
603
604 void Paragraph::setChange(pos_type pos, Change const & change)
605 {
606         LASSERT(pos >= 0 && pos <= size(), /**/);
607         d->changes_.set(change, pos);
608
609         // see comment in setChange(Change const &) above
610         if (!change.deleted() && pos < size())
611                         if (Inset * inset = getInset(pos))
612                                 inset->setChange(change);
613 }
614
615
616 Change const & Paragraph::lookupChange(pos_type pos) const
617 {
618         LASSERT(pos >= 0 && pos <= size(), /**/);
619         return d->changes_.lookup(pos);
620 }
621
622
623 void Paragraph::acceptChanges(pos_type start, pos_type end)
624 {
625         LASSERT(start >= 0 && start <= size(), /**/);
626         LASSERT(end > start && end <= size() + 1, /**/);
627
628         for (pos_type pos = start; pos < end; ++pos) {
629                 switch (lookupChange(pos).type) {
630                         case Change::UNCHANGED:
631                                 // accept changes in nested inset
632                                 if (Inset * inset = getInset(pos))
633                                         inset->acceptChanges();
634                                 break;
635
636                         case Change::INSERTED:
637                                 d->changes_.set(Change(Change::UNCHANGED), pos);
638                                 // also accept changes in nested inset
639                                 if (Inset * inset = getInset(pos))
640                                         inset->acceptChanges();
641                                 break;
642
643                         case Change::DELETED:
644                                 // Suppress access to non-existent
645                                 // "end-of-paragraph char"
646                                 if (pos < size()) {
647                                         eraseChar(pos, false);
648                                         --end;
649                                         --pos;
650                                 }
651                                 break;
652                 }
653
654         }
655 }
656
657
658 void Paragraph::rejectChanges(pos_type start, pos_type end)
659 {
660         LASSERT(start >= 0 && start <= size(), /**/);
661         LASSERT(end > start && end <= size() + 1, /**/);
662
663         for (pos_type pos = start; pos < end; ++pos) {
664                 switch (lookupChange(pos).type) {
665                         case Change::UNCHANGED:
666                                 // reject changes in nested inset
667                                 if (Inset * inset = getInset(pos))
668                                                 inset->rejectChanges();
669                                 break;
670
671                         case Change::INSERTED:
672                                 // Suppress access to non-existent
673                                 // "end-of-paragraph char"
674                                 if (pos < size()) {
675                                         eraseChar(pos, false);
676                                         --end;
677                                         --pos;
678                                 }
679                                 break;
680
681                         case Change::DELETED:
682                                 d->changes_.set(Change(Change::UNCHANGED), pos);
683
684                                 // Do NOT reject changes within a deleted inset!
685                                 // There may be insertions of a co-author inside of it!
686
687                                 break;
688                 }
689         }
690 }
691
692
693 void Paragraph::Private::insertChar(pos_type pos, char_type c,
694                 Change const & change)
695 {
696         LASSERT(pos >= 0 && pos <= int(text_.size()), /**/);
697
698         // track change
699         changes_.insert(change, pos);
700
701         // This is actually very common when parsing buffers (and
702         // maybe inserting ascii text)
703         if (pos == pos_type(text_.size())) {
704                 // when appending characters, no need to update tables
705                 text_.push_back(c);
706                 // but we want spell checking
707                 requestSpellCheck(pos);
708                 return;
709         }
710
711         text_.insert(text_.begin() + pos, c);
712
713         // Update the font table.
714         fontlist_.increasePosAfterPos(pos);
715
716         // Update the insets
717         insetlist_.increasePosAfterPos(pos);
718
719         // Update list of misspelled positions
720         speller_state_.increasePosAfterPos(pos);
721 }
722
723
724 bool Paragraph::insertInset(pos_type pos, Inset * inset,
725                                    Change const & change)
726 {
727         LASSERT(inset, /**/);
728         LASSERT(pos >= 0 && pos <= size(), /**/);
729
730         // Paragraph::insertInset() can be used in cut/copy/paste operation where
731         // d->inset_owner_ is not set yet.
732         if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
733                 return false;
734
735         d->insertChar(pos, META_INSET, change);
736         LASSERT(d->text_[pos] == META_INSET, /**/);
737
738         // Add a new entry in the insetlist_.
739         d->insetlist_.insert(inset, pos);
740
741         // Some insets require run of spell checker
742         requestSpellCheck(pos);
743         return true;
744 }
745
746
747 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
748 {
749         LASSERT(pos >= 0 && pos <= size(), return false);
750
751         // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
752
753         if (trackChanges) {
754                 Change change = d->changes_.lookup(pos);
755
756                 // set the character to DELETED if
757                 //  a) it was previously unchanged or
758                 //  b) it was inserted by a co-author
759
760                 if (!change.changed() ||
761                       (change.inserted() && !change.currentAuthor())) {
762                         setChange(pos, Change(Change::DELETED));
763                         // request run of spell checker
764                         requestSpellCheck(pos);
765                         return false;
766                 }
767
768                 if (change.deleted())
769                         return false;
770         }
771
772         // Don't physically access the imaginary end-of-paragraph character.
773         // eraseChar() can only mark it as DELETED. A physical deletion of
774         // end-of-par must be handled externally.
775         if (pos == size()) {
776                 return false;
777         }
778
779         // track change
780         d->changes_.erase(pos);
781
782         // if it is an inset, delete the inset entry
783         if (d->text_[pos] == META_INSET)
784                 d->insetlist_.erase(pos);
785
786         d->text_.erase(d->text_.begin() + pos);
787
788         // Update the fontlist_
789         d->fontlist_.erase(pos);
790
791         // Update the insetlist_
792         d->insetlist_.decreasePosAfterPos(pos);
793
794         // Update list of misspelled positions
795         d->speller_state_.decreasePosAfterPos(pos);
796         d->speller_state_.refreshLast(size());
797
798         return true;
799 }
800
801
802 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
803 {
804         LASSERT(start >= 0 && start <= size(), /**/);
805         LASSERT(end >= start && end <= size() + 1, /**/);
806
807         pos_type i = start;
808         for (pos_type count = end - start; count; --count) {
809                 if (!eraseChar(i, trackChanges))
810                         ++i;
811         }
812         return end - i;
813 }
814
815
816 int Paragraph::Private::latexSurrogatePair(odocstream & os, char_type c,
817                 char_type next, OutputParams const & runparams)
818 {
819         // Writing next here may circumvent a possible font change between
820         // c and next. Since next is only output if it forms a surrogate pair
821         // with c we can ignore this:
822         // A font change inside a surrogate pair does not make sense and is
823         // hopefully impossible to input.
824         // FIXME: change tracking
825         // Is this correct WRT change tracking?
826         Encoding const & encoding = *(runparams.encoding);
827         docstring const latex1 = encoding.latexChar(next);
828         docstring const latex2 = encoding.latexChar(c);
829         if (docstring(1, next) == latex1) {
830                 // the encoding supports the combination
831                 os << latex2 << latex1;
832                 return latex1.length() + latex2.length();
833         } else if (runparams.local_font &&
834                    runparams.local_font->language()->lang() == "polutonikogreek") {
835                 // polutonikogreek only works without the brackets
836                 os << latex1 << latex2;
837                 return latex1.length() + latex2.length();
838         } else
839                 os << latex1 << '{' << latex2 << '}';
840         return latex1.length() + latex2.length() + 2;
841 }
842
843
844 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
845                                        odocstream & os, TexRow & texrow,
846                                        pos_type i,
847                                        unsigned int & column,
848                                        Font const & font,
849                                        Layout const & style)
850 {
851         if (style.pass_thru || runparams.pass_thru)
852                 return false;
853
854         if (i + 1 < int(text_.size())) {
855                 char_type next = text_[i + 1];
856                 if (Encodings::isCombiningChar(next)) {
857                         // This space has an accent, so we must always output it.
858                         column += latexSurrogatePair(os, ' ', next, runparams) - 1;
859                         return true;
860                 }
861         }
862
863         if (runparams.linelen > 0
864             && column > runparams.linelen
865             && i
866             && text_[i - 1] != ' '
867             && (i + 1 < int(text_.size()))
868             // same in FreeSpacing mode
869             && !owner_->isFreeSpacing()
870             // In typewriter mode, we want to avoid
871             // ! . ? : at the end of a line
872             && !(font.fontInfo().family() == TYPEWRITER_FAMILY
873                  && (text_[i - 1] == '.'
874                      || text_[i - 1] == '?'
875                      || text_[i - 1] == ':'
876                      || text_[i - 1] == '!'))) {
877                 os << '\n';
878                 texrow.newline();
879                 texrow.start(owner_->id(), i + 1);
880                 column = 0;
881         } else if (style.free_spacing) {
882                 os << '~';
883         } else {
884                 os << ' ';
885         }
886         return false;
887 }
888
889
890 int Paragraph::Private::writeScriptChars(odocstream & os,
891                                          docstring const & ltx,
892                                          Change const & runningChange,
893                                          Encoding const & encoding,
894                                          pos_type & i)
895 {
896         // FIXME: modifying i here is not very nice...
897
898         // We only arrive here when a proper language for character text_[i] has
899         // not been specified (i.e., it could not be translated in the current
900         // latex encoding) or its latex translation has been forced, and it
901         // belongs to a known script.
902         // Parameter ltx contains the latex translation of text_[i] as specified
903         // in the unicodesymbols file and is something like "\textXXX{<spec>}".
904         // The latex macro name "textXXX" specifies the script to which text_[i]
905         // belongs and we use it in order to check whether characters from the
906         // same script immediately follow, such that we can collect them in a
907         // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
908         // for the first char but only "<spec>" for all subsequent chars.
909         docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
910         docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
911         string script = to_ascii(ltx.substr(1, brace1 - 1));
912         int pos = 0;
913         int length = brace2;
914         bool closing_brace = true;
915         if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
916                 // Correct encoding is being used, so we can avoid \textgreek.
917                 pos = brace1 + 1;
918                 length -= pos;
919                 closing_brace = false;
920         }
921         os << ltx.substr(pos, length);
922         int size = text_.size();
923         while (i + 1 < size) {
924                 char_type const next = text_[i + 1];
925                 // Stop here if next character belongs to another script
926                 // or there is a change in change tracking status.
927                 if (!Encodings::isKnownScriptChar(next, script) ||
928                     runningChange != owner_->lookupChange(i + 1))
929                         break;
930                 Font prev_font;
931                 bool found = false;
932                 FontList::const_iterator cit = fontlist_.begin();
933                 FontList::const_iterator end = fontlist_.end();
934                 for (; cit != end; ++cit) {
935                         if (cit->pos() >= i && !found) {
936                                 prev_font = cit->font();
937                                 found = true;
938                         }
939                         if (cit->pos() >= i + 1)
940                                 break;
941                 }
942                 // Stop here if there is a font attribute or encoding change.
943                 if (found && cit != end && prev_font != cit->font())
944                         break;
945                 docstring const latex = encoding.latexChar(next);
946                 docstring::size_type const b1 =
947                                         latex.find_first_of(from_ascii("{"));
948                 docstring::size_type const b2 =
949                                         latex.find_last_of(from_ascii("}"));
950                 int const len = b2 - b1 - 1;
951                 os << latex.substr(b1 + 1, len);
952                 length += len;
953                 ++i;
954         }
955         if (closing_brace) {
956                 os << '}';
957                 ++length;
958         }
959         return length;
960 }
961
962
963 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
964 {
965         pos_type const len = str.length();
966
967         // is the paragraph large enough?
968         if (pos + len > int(text_.size()))
969                 return false;
970
971         // does the wanted text start at point?
972         for (string::size_type i = 0; i < str.length(); ++i) {
973                 // Caution: direct comparison of characters works only
974                 // because str is pure ASCII.
975                 if (str[i] != text_[pos + i])
976                         return false;
977         }
978
979         return fontlist_.hasChangeInRange(pos, len);
980 }
981
982
983 void Paragraph::Private::latexInset(BufferParams const & bparams,
984                                     odocstream & os,
985                                     TexRow & texrow,
986                                     OutputParams & runparams,
987                                     Font & running_font,
988                                     Font & basefont,
989                                     Font const & outerfont,
990                                     bool & open_font,
991                                     Change & running_change,
992                                     Layout const & style,
993                                     pos_type & i,
994                                     unsigned int & column)
995 {
996         Inset * inset = owner_->getInset(i);
997         LASSERT(inset, /**/);
998
999         if (style.pass_thru) {
1000                 inset->plaintext(os, runparams);
1001                 return;
1002         }
1003
1004         // FIXME: move this to InsetNewline::latex
1005         if (inset->lyxCode() == NEWLINE_CODE) {
1006                 // newlines are handled differently here than
1007                 // the default in simpleTeXSpecialChars().
1008                 if (!style.newline_allowed) {
1009                         os << '\n';
1010                 } else {
1011                         if (open_font) {
1012                                 column += running_font.latexWriteEndChanges(
1013                                         os, bparams, runparams,
1014                                         basefont, basefont);
1015                                 open_font = false;
1016                         }
1017
1018                         if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
1019                                 os << '~';
1020
1021                         basefont = owner_->getLayoutFont(bparams, outerfont);
1022                         running_font = basefont;
1023
1024                         if (runparams.moving_arg)
1025                                 os << "\\protect ";
1026
1027                 }
1028                 texrow.newline();
1029                 texrow.start(owner_->id(), i + 1);
1030                 column = 0;
1031         }
1032
1033         if (owner_->isDeleted(i)) {
1034                 if( ++runparams.inDeletedInset == 1)
1035                         runparams.changeOfDeletedInset = owner_->lookupChange(i);
1036         }
1037
1038         if (inset->canTrackChanges()) {
1039                 column += Changes::latexMarkChange(os, bparams, running_change,
1040                         Change(Change::UNCHANGED), runparams);
1041                 running_change = Change(Change::UNCHANGED);
1042         }
1043
1044         bool close = false;
1045         odocstream::pos_type const len = os.tellp();
1046
1047         if (inset->forceLTR()
1048             && running_font.isRightToLeft()
1049             // ERT is an exception, it should be output with no
1050             // decorations at all
1051             && inset->lyxCode() != ERT_CODE) {
1052                 if (running_font.language()->lang() == "farsi")
1053                         os << "\\beginL{}";
1054                 else
1055                         os << "\\L{";
1056                 close = true;
1057         }
1058
1059         // FIXME: Bug: we can have an empty font change here!
1060         // if there has just been a font change, we are going to close it
1061         // right now, which means stupid latex code like \textsf{}. AFAIK,
1062         // this does not harm dvi output. A minor bug, thus (JMarc)
1063
1064         // Some insets cannot be inside a font change command.
1065         // However, even such insets *can* be placed in \L or \R
1066         // or their equivalents (for RTL language switches), so we don't
1067         // close the language in those cases.
1068         // ArabTeX, though, cannot handle this special behavior, it seems.
1069         bool arabtex = basefont.language()->lang() == "arabic_arabtex"
1070                 || running_font.language()->lang() == "arabic_arabtex";
1071         if (open_font && inset->noFontChange()) {
1072                 bool closeLanguage = arabtex
1073                         || basefont.isRightToLeft() == running_font.isRightToLeft();
1074                 unsigned int count = running_font.latexWriteEndChanges(os,
1075                         bparams, runparams, basefont, basefont, closeLanguage);
1076                 column += count;
1077                 // if any font properties were closed, update the running_font,
1078                 // making sure, however, to leave the language as it was
1079                 if (count > 0) {
1080                         // FIXME: probably a better way to keep track of the old
1081                         // language, than copying the entire font?
1082                         Font const copy_font(running_font);
1083                         basefont = owner_->getLayoutFont(bparams, outerfont);
1084                         running_font = basefont;
1085                         if (!closeLanguage)
1086                                 running_font.setLanguage(copy_font.language());
1087                         // leave font open if language is still open
1088                         open_font = (running_font.language() == basefont.language());
1089                         if (closeLanguage)
1090                                 runparams.local_font = &basefont;
1091                 }
1092         }
1093
1094         int tmp;
1095
1096         try {
1097                 tmp = inset->latex(os, runparams);
1098         } catch (EncodingException & e) {
1099                 // add location information and throw again.
1100                 e.par_id = id_;
1101                 e.pos = i;
1102                 throw(e);
1103         }
1104
1105         if (close) {
1106                 if (running_font.language()->lang() == "farsi")
1107                                 os << "\\endL{}";
1108                         else
1109                                 os << '}';
1110         }
1111
1112         if (tmp) {
1113                 texrow.newlines(tmp);
1114                 texrow.start(owner_->id(), i + 1);
1115                 column = 0;
1116         } else {
1117                 column += (unsigned int)(os.tellp() - len);
1118         }
1119
1120         if (owner_->isDeleted(i))
1121                 --runparams.inDeletedInset;
1122 }
1123
1124
1125 void Paragraph::Private::latexSpecialChar(
1126                                              odocstream & os,
1127                                              OutputParams const & runparams,
1128                                              Font const & running_font,
1129                                              Change const & running_change,
1130                                              Layout const & style,
1131                                              pos_type & i,
1132                                              unsigned int & column)
1133 {
1134         char_type const c = text_[i];
1135
1136         if (style.pass_thru || runparams.pass_thru) {
1137                 if (c != '\0')
1138                         // FIXME UNICODE: This can fail if c cannot
1139                         // be encoded in the current encoding.
1140                         os.put(c);
1141                 return;
1142         }
1143
1144         // If T1 font encoding is used, use the special
1145         // characters it provides.
1146         // NOTE: some languages reset the font encoding
1147         // internally
1148         if (!running_font.language()->internalFontEncoding()
1149             && lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
1150                 return;
1151
1152         // \tt font needs special treatment
1153         if (running_font.fontInfo().family() == TYPEWRITER_FAMILY
1154                 && latexSpecialTypewriter(c, os, i, column))
1155                 return;
1156
1157         // Otherwise, we use what LaTeX provides us.
1158         switch (c) {
1159         case '\\':
1160                 os << "\\textbackslash{}";
1161                 column += 15;
1162                 break;
1163         case '<':
1164                 os << "\\textless{}";
1165                 column += 10;
1166                 break;
1167         case '>':
1168                 os << "\\textgreater{}";
1169                 column += 13;
1170                 break;
1171         case '|':
1172                 os << "\\textbar{}";
1173                 column += 9;
1174                 break;
1175         case '-':
1176                 os << '-';
1177                 break;
1178         case '\"':
1179                 os << "\\char`\\\"{}";
1180                 column += 9;
1181                 break;
1182
1183         case '$': case '&':
1184         case '%': case '#': case '{':
1185         case '}': case '_':
1186                 os << '\\';
1187                 os.put(c);
1188                 column += 1;
1189                 break;
1190
1191         case '~':
1192                 os << "\\textasciitilde{}";
1193                 column += 16;
1194                 break;
1195
1196         case '^':
1197                 os << "\\textasciicircum{}";
1198                 column += 17;
1199                 break;
1200
1201         case '*':
1202         case '[':
1203         case ']':
1204                 // avoid being mistaken for optional arguments
1205                 os << '{';
1206                 os.put(c);
1207                 os << '}';
1208                 column += 2;
1209                 break;
1210
1211         case ' ':
1212                 // Blanks are printed before font switching.
1213                 // Sure? I am not! (try nice-latex)
1214                 // I am sure it's correct. LyX might be smarter
1215                 // in the future, but for now, nothing wrong is
1216                 // written. (Asger)
1217                 break;
1218
1219         default:
1220                 // LyX, LaTeX etc.
1221                 if (latexSpecialPhrase(os, i, column, runparams))
1222                         return;
1223
1224                 if (c == '\0')
1225                         return;
1226
1227                 Encoding const & encoding = *(runparams.encoding);
1228                 if (i + 1 < int(text_.size())) {
1229                         char_type next = text_[i + 1];
1230                         if (Encodings::isCombiningChar(next)) {
1231                                 column += latexSurrogatePair(os, c, next, runparams) - 1;
1232                                 ++i;
1233                                 break;
1234                         }
1235                 }
1236                 string script;
1237                 docstring const latex = encoding.latexChar(c);
1238                 if (Encodings::isKnownScriptChar(c, script)
1239                     && prefixIs(latex, from_ascii("\\" + script)))
1240                         column += writeScriptChars(os, latex,
1241                                         running_change, encoding, i) - 1;
1242                 else if (latex.length() > 1 && latex[latex.length() - 1] != '}') {
1243                         // Prevent eating of a following
1244                         // space or command corruption by
1245                         // following characters
1246                         column += latex.length() + 1;
1247                         os << latex << "{}";
1248                 } else {
1249                         column += latex.length() - 1;
1250                         os << latex;
1251                 }
1252                 break;
1253         }
1254 }
1255
1256
1257 bool Paragraph::Private::latexSpecialT1(char_type const c, odocstream & os,
1258         pos_type i, unsigned int & column)
1259 {
1260         switch (c) {
1261         case '>':
1262         case '<':
1263                 os.put(c);
1264                 // In T1 encoding, these characters exist
1265                 // but we should avoid ligatures
1266                 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1267                         return true;
1268                 os << "\\textcompwordmark{}";
1269                 column += 19;
1270                 return true;
1271         case '|':
1272                 os.put(c);
1273                 return true;
1274         case '\"':
1275                 // soul.sty breaks with \char`\"
1276                 os << "\\textquotedbl{}";
1277                 column += 14;
1278                 return true;
1279         default:
1280                 return false;
1281         }
1282 }
1283
1284
1285 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, odocstream & os,
1286         pos_type i, unsigned int & column)
1287 {
1288         switch (c) {
1289         case '-':
1290                 // within \ttfamily, "--" is merged to "-" (no endash)
1291                 // so we avoid this rather irritating ligature
1292                 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
1293                         os << "-{}";
1294                         column += 2;
1295                 } else
1296                         os << '-';
1297                 return true;
1298
1299         // everything else has to be checked separately
1300         // (depending on the encoding)
1301         default:
1302                 return false;
1303         }
1304 }
1305
1306
1307 bool Paragraph::Private::latexSpecialPhrase(odocstream & os, pos_type & i,
1308         unsigned int & column, OutputParams const & runparams)
1309 {
1310         // FIXME: if we have "LaTeX" with a font
1311         // change in the middle (before the 'T', then
1312         // the "TeX" part is still special cased.
1313         // Really we should only operate this on
1314         // "words" for some definition of word
1315
1316         for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1317                 if (!isTextAt(special_phrases[pnr].phrase, i))
1318                         continue;
1319                 if (runparams.moving_arg)
1320                         os << "\\protect";
1321                 os << special_phrases[pnr].macro;
1322                 i += special_phrases[pnr].phrase.length() - 1;
1323                 column += special_phrases[pnr].macro.length() - 1;
1324                 return true;
1325         }
1326         return false;
1327 }
1328
1329
1330 void Paragraph::Private::validate(LaTeXFeatures & features) const
1331 {
1332         if (layout_->inpreamble && inset_owner_) {
1333                 bool const is_command = layout_->latextype == LATEX_COMMAND;
1334                 Buffer const & buf = inset_owner_->buffer();
1335                 BufferParams const & bp = buf.params();
1336                 Font f;
1337                 TexRow tr;
1338                 // Using a string stream here circumvents the encoding
1339                 // switching machinery of odocstream. Therefore the
1340                 // output is wrong if this paragraph contains content
1341                 // that needs to switch encoding.
1342                 odocstringstream ods;
1343                 if (is_command) {
1344                         ods << '\\' << from_ascii(layout_->latexname());
1345                         // we have to provide all the optional arguments here, even though
1346                         // the last one is the only one we care about.
1347                         // Separate handling of optional argument inset.
1348                         if (layout_->optargs != 0 || layout_->reqargs != 0)
1349                                 latexArgInsets(*owner_, ods, features.runparams(),
1350                                                                                          layout_->reqargs, layout_->optargs);
1351                         else
1352                                 ods << from_ascii(layout_->latexparam());
1353                 }
1354                 docstring::size_type const length = ods.str().length();
1355                 // this will output "{" at the beginning, but not at the end
1356                 owner_->latex(bp, f, ods, tr, features.runparams(), 0, -1, true);
1357                 if (ods.str().length() > length) {
1358                         if (is_command)
1359                                 ods << '}';
1360                         string const snippet = to_utf8(ods.str());
1361                         features.addPreambleSnippet(snippet);
1362                 }
1363         }
1364
1365         if (features.runparams().flavor == OutputParams::HTML
1366             && layout_->htmltitle()) {
1367                 features.setHTMLTitle(owner_->asString(AS_STR_INSETS));
1368         }
1369
1370         // check the params.
1371         if (!params_.spacing().isDefault())
1372                 features.require("setspace");
1373
1374         // then the layouts
1375         features.useLayout(layout_->name());
1376
1377         // then the fonts
1378         fontlist_.validate(features);
1379
1380         // then the indentation
1381         if (!params_.leftIndent().zero())
1382                 features.require("ParagraphLeftIndent");
1383
1384         // then the insets
1385         InsetList::const_iterator icit = insetlist_.begin();
1386         InsetList::const_iterator iend = insetlist_.end();
1387         for (; icit != iend; ++icit) {
1388                 if (icit->inset) {
1389                         icit->inset->validate(features);
1390                         if (layout_->needprotect &&
1391                             icit->inset->lyxCode() == FOOT_CODE)
1392                                 features.require("NeedLyXFootnoteCode");
1393                 }
1394         }
1395
1396         // then the contents
1397         for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1398                 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1399                         if (!special_phrases[pnr].builtin
1400                             && isTextAt(special_phrases[pnr].phrase, i)) {
1401                                 features.require(special_phrases[pnr].phrase);
1402                                 break;
1403                         }
1404                 }
1405                 Encodings::validate(text_[i], features);
1406         }
1407 }
1408
1409 /////////////////////////////////////////////////////////////////////
1410 //
1411 // Paragraph
1412 //
1413 /////////////////////////////////////////////////////////////////////
1414
1415 namespace {
1416         Layout const emptyParagraphLayout;
1417 }
1418
1419 Paragraph::Paragraph()
1420         : d(new Paragraph::Private(this, emptyParagraphLayout))
1421 {
1422         itemdepth = 0;
1423         d->params_.clear();
1424 }
1425
1426
1427 Paragraph::Paragraph(Paragraph const & par)
1428         : itemdepth(par.itemdepth),
1429         d(new Paragraph::Private(*par.d, this))
1430 {
1431         registerWords();
1432 }
1433
1434
1435 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1436         : itemdepth(par.itemdepth),
1437         d(new Paragraph::Private(*par.d, this, beg, end))
1438 {
1439         registerWords();
1440 }
1441
1442
1443 Paragraph & Paragraph::operator=(Paragraph const & par)
1444 {
1445         // needed as we will destroy the private part before copying it
1446         if (&par != this) {
1447                 itemdepth = par.itemdepth;
1448
1449                 deregisterWords();
1450                 delete d;
1451                 d = new Private(*par.d, this);
1452                 registerWords();
1453         }
1454         return *this;
1455 }
1456
1457
1458 Paragraph::~Paragraph()
1459 {
1460         deregisterWords();
1461         delete d;
1462 }
1463
1464
1465 namespace {
1466
1467 // this shall be called just before every "os << ..." action.
1468 void flushString(ostream & os, docstring & s)
1469 {
1470         os << to_utf8(s);
1471         s.erase();
1472 }
1473
1474 }
1475
1476
1477 void Paragraph::write(ostream & os, BufferParams const & bparams,
1478         depth_type & dth) const
1479 {
1480         // The beginning or end of a deeper (i.e. nested) area?
1481         if (dth != d->params_.depth()) {
1482                 if (d->params_.depth() > dth) {
1483                         while (d->params_.depth() > dth) {
1484                                 os << "\n\\begin_deeper";
1485                                 ++dth;
1486                         }
1487                 } else {
1488                         while (d->params_.depth() < dth) {
1489                                 os << "\n\\end_deeper";
1490                                 --dth;
1491                         }
1492                 }
1493         }
1494
1495         // First write the layout
1496         os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1497
1498         d->params_.write(os);
1499
1500         Font font1(inherit_font, bparams.language);
1501
1502         Change running_change = Change(Change::UNCHANGED);
1503
1504         // this string is used as a buffer to avoid repetitive calls
1505         // to to_utf8(), which turn out to be expensive (JMarc)
1506         docstring write_buffer;
1507
1508         int column = 0;
1509         for (pos_type i = 0; i <= size(); ++i) {
1510
1511                 Change const change = lookupChange(i);
1512                 if (change != running_change)
1513                         flushString(os, write_buffer);
1514                 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1515                 running_change = change;
1516
1517                 if (i == size())
1518                         break;
1519
1520                 // Write font changes
1521                 Font font2 = getFontSettings(bparams, i);
1522                 if (font2 != font1) {
1523                         flushString(os, write_buffer);
1524                         font2.lyxWriteChanges(font1, os);
1525                         column = 0;
1526                         font1 = font2;
1527                 }
1528
1529                 char_type const c = d->text_[i];
1530                 switch (c) {
1531                 case META_INSET:
1532                         if (Inset const * inset = getInset(i)) {
1533                                 flushString(os, write_buffer);
1534                                 if (inset->directWrite()) {
1535                                         // international char, let it write
1536                                         // code directly so it's shorter in
1537                                         // the file
1538                                         inset->write(os);
1539                                 } else {
1540                                         if (i)
1541                                                 os << '\n';
1542                                         os << "\\begin_inset ";
1543                                         inset->write(os);
1544                                         os << "\n\\end_inset\n\n";
1545                                         column = 0;
1546                                 }
1547                         }
1548                         break;
1549                 case '\\':
1550                         flushString(os, write_buffer);
1551                         os << "\n\\backslash\n";
1552                         column = 0;
1553                         break;
1554                 case '.':
1555                         flushString(os, write_buffer);
1556                         if (i + 1 < size() && d->text_[i + 1] == ' ') {
1557                                 os << ".\n";
1558                                 column = 0;
1559                         } else
1560                                 os << '.';
1561                         break;
1562                 default:
1563                         if ((column > 70 && c == ' ')
1564                             || column > 79) {
1565                                 flushString(os, write_buffer);
1566                                 os << '\n';
1567                                 column = 0;
1568                         }
1569                         // this check is to amend a bug. LyX sometimes
1570                         // inserts '\0' this could cause problems.
1571                         if (c != '\0')
1572                                 write_buffer.push_back(c);
1573                         else
1574                                 LYXERR0("NUL char in structure.");
1575                         ++column;
1576                         break;
1577                 }
1578         }
1579
1580         flushString(os, write_buffer);
1581         os << "\n\\end_layout\n";
1582 }
1583
1584
1585 void Paragraph::validate(LaTeXFeatures & features) const
1586 {
1587         d->validate(features);
1588 }
1589
1590
1591 void Paragraph::insert(pos_type start, docstring const & str,
1592                        Font const & font, Change const & change)
1593 {
1594         for (size_t i = 0, n = str.size(); i != n ; ++i)
1595                 insertChar(start + i, str[i], font, change);
1596 }
1597
1598
1599 void Paragraph::appendChar(char_type c, Font const & font,
1600                 Change const & change)
1601 {
1602         // track change
1603         d->changes_.insert(change, d->text_.size());
1604         // when appending characters, no need to update tables
1605         d->text_.push_back(c);
1606         setFont(d->text_.size() - 1, font);
1607 }
1608
1609
1610 void Paragraph::appendString(docstring const & s, Font const & font,
1611                 Change const & change)
1612 {
1613         pos_type end = s.size();
1614         size_t oldsize = d->text_.size();
1615         size_t newsize = oldsize + end;
1616         size_t capacity = d->text_.capacity();
1617         if (newsize >= capacity)
1618                 d->text_.reserve(max(capacity + 100, newsize));
1619
1620         // when appending characters, no need to update tables
1621         d->text_.append(s);
1622
1623         // FIXME: Optimize this!
1624         for (size_t i = oldsize; i != newsize; ++i) {
1625                 // track change
1626                 d->changes_.insert(change, i);
1627         }
1628         d->fontlist_.set(oldsize, font);
1629         d->fontlist_.set(newsize - 1, font);
1630 }
1631
1632
1633 void Paragraph::insertChar(pos_type pos, char_type c,
1634                            bool trackChanges)
1635 {
1636         d->insertChar(pos, c, Change(trackChanges ?
1637                            Change::INSERTED : Change::UNCHANGED));
1638 }
1639
1640
1641 void Paragraph::insertChar(pos_type pos, char_type c,
1642                            Font const & font, bool trackChanges)
1643 {
1644         d->insertChar(pos, c, Change(trackChanges ?
1645                            Change::INSERTED : Change::UNCHANGED));
1646         setFont(pos, font);
1647 }
1648
1649
1650 void Paragraph::insertChar(pos_type pos, char_type c,
1651                            Font const & font, Change const & change)
1652 {
1653         d->insertChar(pos, c, change);
1654         setFont(pos, font);
1655 }
1656
1657
1658 bool Paragraph::insertInset(pos_type pos, Inset * inset,
1659                             Font const & font, Change const & change)
1660 {
1661         bool const success = insertInset(pos, inset, change);
1662         // Set the font/language of the inset...
1663         setFont(pos, font);
1664         return success;
1665 }
1666
1667
1668 void Paragraph::resetFonts(Font const & font)
1669 {
1670         d->fontlist_.clear();
1671         d->fontlist_.set(0, font);
1672         d->fontlist_.set(d->text_.size() - 1, font);
1673 }
1674
1675 // Gets uninstantiated font setting at position.
1676 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1677                                          pos_type pos) const
1678 {
1679         if (pos > size()) {
1680                 LYXERR0("pos: " << pos << " size: " << size());
1681                 LASSERT(pos <= size(), /**/);
1682         }
1683
1684         FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1685         if (cit != d->fontlist_.end())
1686                 return cit->font();
1687
1688         if (pos == size() && !empty())
1689                 return getFontSettings(bparams, pos - 1);
1690
1691         // Optimisation: avoid a full font instantiation if there is no
1692         // language change from previous call.
1693         static Font previous_font;
1694         static Language const * previous_lang = 0;
1695         Language const * lang = getParLanguage(bparams);
1696         if (lang != previous_lang) {
1697                 previous_lang = lang;
1698                 previous_font = Font(inherit_font, lang);
1699         }
1700         return previous_font;
1701 }
1702
1703
1704 FontSpan Paragraph::fontSpan(pos_type pos) const
1705 {
1706         LASSERT(pos <= size(), /**/);
1707         pos_type start = 0;
1708
1709         FontList::const_iterator cit = d->fontlist_.begin();
1710         FontList::const_iterator end = d->fontlist_.end();
1711         for (; cit != end; ++cit) {
1712                 if (cit->pos() >= pos) {
1713                         if (pos >= beginOfBody())
1714                                 return FontSpan(max(start, beginOfBody()),
1715                                                 cit->pos());
1716                         else
1717                                 return FontSpan(start,
1718                                                 min(beginOfBody() - 1,
1719                                                          cit->pos()));
1720                 }
1721                 start = cit->pos() + 1;
1722         }
1723
1724         // This should not happen, but if so, we take no chances.
1725         // LYXERR0("Paragraph::getEndPosOfFontSpan: This should not happen!");
1726         return FontSpan(pos, pos);
1727 }
1728
1729
1730 // Gets uninstantiated font setting at position 0
1731 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1732 {
1733         if (!empty() && !d->fontlist_.empty())
1734                 return d->fontlist_.begin()->font();
1735
1736         // Optimisation: avoid a full font instantiation if there is no
1737         // language change from previous call.
1738         static Font previous_font;
1739         static Language const * previous_lang = 0;
1740         if (bparams.language != previous_lang) {
1741                 previous_lang = bparams.language;
1742                 previous_font = Font(inherit_font, bparams.language);
1743         }
1744
1745         return previous_font;
1746 }
1747
1748
1749 // Gets the fully instantiated font at a given position in a paragraph
1750 // This is basically the same function as Text::GetFont() in text2.cpp.
1751 // The difference is that this one is used for generating the LaTeX file,
1752 // and thus cosmetic "improvements" are disallowed: This has to deliver
1753 // the true picture of the buffer. (Asger)
1754 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1755                                  Font const & outerfont) const
1756 {
1757         LASSERT(pos >= 0, /**/);
1758
1759         Font font = getFontSettings(bparams, pos);
1760
1761         pos_type const body_pos = beginOfBody();
1762         FontInfo & fi = font.fontInfo();
1763         if (pos < body_pos)
1764                 fi.realize(d->layout_->labelfont);
1765         else
1766                 fi.realize(d->layout_->font);
1767
1768         fi.realize(outerfont.fontInfo());
1769         fi.realize(bparams.getFont().fontInfo());
1770
1771         return font;
1772 }
1773
1774
1775 Font const Paragraph::getLabelFont
1776         (BufferParams const & bparams, Font const & outerfont) const
1777 {
1778         FontInfo tmpfont = d->layout_->labelfont;
1779         tmpfont.realize(outerfont.fontInfo());
1780         tmpfont.realize(bparams.getFont().fontInfo());
1781         return Font(tmpfont, getParLanguage(bparams));
1782 }
1783
1784
1785 Font const Paragraph::getLayoutFont
1786         (BufferParams const & bparams, Font const & outerfont) const
1787 {
1788         FontInfo tmpfont = d->layout_->font;
1789         tmpfont.realize(outerfont.fontInfo());
1790         tmpfont.realize(bparams.getFont().fontInfo());
1791         return Font(tmpfont, getParLanguage(bparams));
1792 }
1793
1794
1795 /// Returns the height of the highest font in range
1796 FontSize Paragraph::highestFontInRange
1797         (pos_type startpos, pos_type endpos, FontSize def_size) const
1798 {
1799         return d->fontlist_.highestInRange(startpos, endpos, def_size);
1800 }
1801
1802
1803 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1804 {
1805         char_type c = d->text_[pos];
1806         if (!lyxrc.rtl_support)
1807                 return c;
1808
1809         char_type uc = c;
1810         switch (c) {
1811         case '(':
1812                 uc = ')';
1813                 break;
1814         case ')':
1815                 uc = '(';
1816                 break;
1817         case '[':
1818                 uc = ']';
1819                 break;
1820         case ']':
1821                 uc = '[';
1822                 break;
1823         case '{':
1824                 uc = '}';
1825                 break;
1826         case '}':
1827                 uc = '{';
1828                 break;
1829         case '<':
1830                 uc = '>';
1831                 break;
1832         case '>':
1833                 uc = '<';
1834                 break;
1835         }
1836         if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1837                 return uc;
1838         return c;
1839 }
1840
1841
1842 void Paragraph::setFont(pos_type pos, Font const & font)
1843 {
1844         LASSERT(pos <= size(), /**/);
1845
1846         // First, reduce font against layout/label font
1847         // Update: The setCharFont() routine in text2.cpp already
1848         // reduces font, so we don't need to do that here. (Asger)
1849
1850         d->fontlist_.set(pos, font);
1851 }
1852
1853
1854 void Paragraph::makeSameLayout(Paragraph const & par)
1855 {
1856         d->layout_ = par.d->layout_;
1857         d->params_ = par.d->params_;
1858 }
1859
1860
1861 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1862 {
1863         if (isFreeSpacing())
1864                 return false;
1865
1866         int pos = 0;
1867         int count = 0;
1868
1869         while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1870                 if (eraseChar(pos, trackChanges))
1871                         ++count;
1872                 else
1873                         ++pos;
1874         }
1875
1876         return count > 0 || pos > 0;
1877 }
1878
1879
1880 bool Paragraph::hasSameLayout(Paragraph const & par) const
1881 {
1882         return par.d->layout_ == d->layout_
1883                 && d->params_.sameLayout(par.d->params_);
1884 }
1885
1886
1887 depth_type Paragraph::getDepth() const
1888 {
1889         return d->params_.depth();
1890 }
1891
1892
1893 depth_type Paragraph::getMaxDepthAfter() const
1894 {
1895         if (d->layout_->isEnvironment())
1896                 return d->params_.depth() + 1;
1897         else
1898                 return d->params_.depth();
1899 }
1900
1901
1902 char Paragraph::getAlign() const
1903 {
1904         if (d->params_.align() == LYX_ALIGN_LAYOUT)
1905                 return d->layout_->align;
1906         else
1907                 return d->params_.align();
1908 }
1909
1910
1911 docstring const & Paragraph::labelString() const
1912 {
1913         return d->params_.labelString();
1914 }
1915
1916
1917 // the next two functions are for the manual labels
1918 docstring const Paragraph::getLabelWidthString() const
1919 {
1920         if (d->layout_->margintype == MARGIN_MANUAL
1921             || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
1922                 return d->params_.labelWidthString();
1923         else
1924                 return _("Senseless with this layout!");
1925 }
1926
1927
1928 void Paragraph::setLabelWidthString(docstring const & s)
1929 {
1930         d->params_.labelWidthString(s);
1931 }
1932
1933
1934 docstring Paragraph::expandLabel(Layout const & layout,
1935                 BufferParams const & bparams) const
1936 {
1937         return expandParagraphLabel(layout, bparams, true);
1938 }
1939
1940
1941 docstring Paragraph::expandDocBookLabel(Layout const & layout,
1942                 BufferParams const & bparams) const
1943 {
1944         return expandParagraphLabel(layout, bparams, false);
1945 }
1946
1947
1948 docstring Paragraph::expandParagraphLabel(Layout const & layout,
1949                 BufferParams const & bparams, bool process_appendix) const
1950 {
1951         DocumentClass const & tclass = bparams.documentClass();
1952         string const & lang = getParLanguage(bparams)->code();
1953         bool const in_appendix = process_appendix && d->params_.appendix();
1954         docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
1955
1956         if (fmt.empty() && layout.labeltype == LABEL_COUNTER
1957             && !layout.counter.empty())
1958                 return tclass.counters().theCounter(layout.counter, lang);
1959
1960         // handle 'inherited level parts' in 'fmt',
1961         // i.e. the stuff between '@' in   '@Section@.\arabic{subsection}'
1962         size_t const i = fmt.find('@', 0);
1963         if (i != docstring::npos) {
1964                 size_t const j = fmt.find('@', i + 1);
1965                 if (j != docstring::npos) {
1966                         docstring parent(fmt, i + 1, j - i - 1);
1967                         docstring label = from_ascii("??");
1968                         if (tclass.hasLayout(parent))
1969                                 docstring label = expandParagraphLabel(tclass[parent], bparams,
1970                                                       process_appendix);
1971                         fmt = docstring(fmt, 0, i) + label
1972                                 + docstring(fmt, j + 1, docstring::npos);
1973                 }
1974         }
1975
1976         return tclass.counters().counterLabel(fmt, lang);
1977 }
1978
1979
1980 void Paragraph::applyLayout(Layout const & new_layout)
1981 {
1982         d->layout_ = &new_layout;
1983         LyXAlignment const oldAlign = d->params_.align();
1984
1985         if (!(oldAlign & d->layout_->alignpossible)) {
1986                 frontend::Alert::warning(_("Alignment not permitted"),
1987                         _("The new layout does not permit the alignment previously used.\nSetting to default."));
1988                 d->params_.align(LYX_ALIGN_LAYOUT);
1989         }
1990 }
1991
1992
1993 pos_type Paragraph::beginOfBody() const
1994 {
1995         return d->begin_of_body_;
1996 }
1997
1998
1999 void Paragraph::setBeginOfBody()
2000 {
2001         if (d->layout_->labeltype != LABEL_MANUAL) {
2002                 d->begin_of_body_ = 0;
2003                 return;
2004         }
2005
2006         // Unroll the first two cycles of the loop
2007         // and remember the previous character to
2008         // remove unnecessary getChar() calls
2009         pos_type i = 0;
2010         pos_type end = size();
2011         if (i < end && !isNewline(i)) {
2012                 ++i;
2013                 char_type previous_char = 0;
2014                 char_type temp = 0;
2015                 if (i < end) {
2016                         previous_char = d->text_[i];
2017                         if (!isNewline(i)) {
2018                                 ++i;
2019                                 while (i < end && previous_char != ' ') {
2020                                         temp = d->text_[i];
2021                                         if (isNewline(i))
2022                                                 break;
2023                                         ++i;
2024                                         previous_char = temp;
2025                                 }
2026                         }
2027                 }
2028         }
2029
2030         d->begin_of_body_ = i;
2031 }
2032
2033
2034 bool Paragraph::allowParagraphCustomization() const
2035 {
2036         return inInset().allowParagraphCustomization();
2037 }
2038
2039
2040 bool Paragraph::usePlainLayout() const
2041 {
2042         return inInset().usePlainLayout();
2043 }
2044
2045
2046 namespace {
2047
2048 // paragraphs inside floats need different alignment tags to avoid
2049 // unwanted space
2050
2051 bool noTrivlistCentering(InsetCode code)
2052 {
2053         return code == FLOAT_CODE
2054                || code == WRAP_CODE
2055                || code == CELL_CODE;
2056 }
2057
2058
2059 string correction(string const & orig)
2060 {
2061         if (orig == "flushleft")
2062                 return "raggedright";
2063         if (orig == "flushright")
2064                 return "raggedleft";
2065         if (orig == "center")
2066                 return "centering";
2067         return orig;
2068 }
2069
2070
2071 string const corrected_env(string const & suffix, string const & env,
2072         InsetCode code, bool const lastpar)
2073 {
2074         string output = suffix + "{";
2075         if (noTrivlistCentering(code)) {
2076                 if (lastpar) {
2077                         // the last paragraph in non-trivlist-aligned
2078                         // context is special (to avoid unwanted whitespace)
2079                         if (suffix == "\\begin")
2080                                 return "\\" + correction(env) + "{}";
2081                         return string();
2082                 }
2083                 output += correction(env);
2084         } else
2085                 output += env;
2086         output += "}";
2087         if (suffix == "\\begin")
2088                 output += "\n";
2089         return output;
2090 }
2091
2092
2093 void adjust_row_column(string const & str, TexRow & texrow, int & column)
2094 {
2095         if (!contains(str, "\n"))
2096                 column += str.size();
2097         else {
2098                 string tmp;
2099                 texrow.newline();
2100                 column = rsplit(str, tmp, '\n').size();
2101         }
2102 }
2103
2104 } // namespace anon
2105
2106
2107 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2108                                  odocstream & os, TexRow & texrow,
2109                                  OutputParams const & runparams) const
2110 {
2111         int column = 0;
2112
2113         if (params_.noindent()) {
2114                 os << "\\noindent ";
2115                 column += 10;
2116         }
2117
2118         LyXAlignment const curAlign = params_.align();
2119
2120         if (curAlign == layout_->align)
2121                 return column;
2122
2123         switch (curAlign) {
2124         case LYX_ALIGN_NONE:
2125         case LYX_ALIGN_BLOCK:
2126         case LYX_ALIGN_LAYOUT:
2127         case LYX_ALIGN_SPECIAL:
2128         case LYX_ALIGN_DECIMAL:
2129                 break;
2130         case LYX_ALIGN_LEFT:
2131         case LYX_ALIGN_RIGHT:
2132         case LYX_ALIGN_CENTER:
2133                 if (runparams.moving_arg) {
2134                         os << "\\protect";
2135                         column += 8;
2136                 }
2137                 break;
2138         }
2139
2140         string const begin_tag = "\\begin";
2141         InsetCode code = ownerCode();
2142         bool const lastpar = runparams.isLastPar;
2143
2144         switch (curAlign) {
2145         case LYX_ALIGN_NONE:
2146         case LYX_ALIGN_BLOCK:
2147         case LYX_ALIGN_LAYOUT:
2148         case LYX_ALIGN_SPECIAL:
2149         case LYX_ALIGN_DECIMAL:
2150                 break;
2151         case LYX_ALIGN_LEFT: {
2152                 string output;
2153                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2154                         output = corrected_env(begin_tag, "flushleft", code, lastpar);
2155                 else
2156                         output = corrected_env(begin_tag, "flushright", code, lastpar);
2157                 os << from_ascii(output);
2158                 adjust_row_column(output, texrow, column);
2159                 break;
2160         } case LYX_ALIGN_RIGHT: {
2161                 string output;
2162                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2163                         output = corrected_env(begin_tag, "flushright", code, lastpar);
2164                 else
2165                         output = corrected_env(begin_tag, "flushleft", code, lastpar);
2166                 os << from_ascii(output);
2167                 adjust_row_column(output, texrow, column);
2168                 break;
2169         } case LYX_ALIGN_CENTER: {
2170                 string output;
2171                 output = corrected_env(begin_tag, "center", code, lastpar);
2172                 os << from_ascii(output);
2173                 adjust_row_column(output, texrow, column);
2174                 break;
2175         }
2176         }
2177
2178         return column;
2179 }
2180
2181
2182 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2183                                odocstream & os, TexRow & texrow,
2184                                OutputParams const & runparams) const
2185 {
2186         int column = 0;
2187
2188         LyXAlignment const curAlign = params_.align();
2189
2190         if (curAlign == layout_->align)
2191                 return column;
2192
2193         switch (curAlign) {
2194         case LYX_ALIGN_NONE:
2195         case LYX_ALIGN_BLOCK:
2196         case LYX_ALIGN_LAYOUT:
2197         case LYX_ALIGN_SPECIAL:
2198         case LYX_ALIGN_DECIMAL:
2199                 break;
2200         case LYX_ALIGN_LEFT:
2201         case LYX_ALIGN_RIGHT:
2202         case LYX_ALIGN_CENTER:
2203                 if (runparams.moving_arg) {
2204                         os << "\\protect";
2205                         column = 8;
2206                 }
2207                 break;
2208         }
2209
2210         string const end_tag = "\n\\par\\end";
2211         InsetCode code = ownerCode();
2212         bool const lastpar = runparams.isLastPar;
2213
2214         switch (curAlign) {
2215         case LYX_ALIGN_NONE:
2216         case LYX_ALIGN_BLOCK:
2217         case LYX_ALIGN_LAYOUT:
2218         case LYX_ALIGN_SPECIAL:
2219         case LYX_ALIGN_DECIMAL:
2220                 break;
2221         case LYX_ALIGN_LEFT: {
2222                 string output;
2223                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2224                         output = corrected_env(end_tag, "flushleft", code, lastpar);
2225                 else
2226                         output = corrected_env(end_tag, "flushright", code, lastpar);
2227                 os << from_ascii(output);
2228                 adjust_row_column(output, texrow, column);
2229                 break;
2230         } case LYX_ALIGN_RIGHT: {
2231                 string output;
2232                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2233                         output = corrected_env(end_tag, "flushright", code, lastpar);
2234                 else
2235                         output = corrected_env(end_tag, "flushleft", code, lastpar);
2236                 os << from_ascii(output);
2237                 adjust_row_column(output, texrow, column);
2238                 break;
2239         } case LYX_ALIGN_CENTER: {
2240                 string output;
2241                 output = corrected_env(end_tag, "center", code, lastpar);
2242                 os << from_ascii(output);
2243                 adjust_row_column(output, texrow, column);
2244                 break;
2245         }
2246         }
2247
2248         return column;
2249 }
2250
2251
2252 // This one spits out the text of the paragraph
2253 void Paragraph::latex(BufferParams const & bparams,
2254         Font const & outerfont,
2255         odocstream & os, TexRow & texrow,
2256         OutputParams const & runparams,
2257         int start_pos, int end_pos, bool force) const
2258 {
2259         LYXERR(Debug::LATEX, "Paragraph::latex...     " << this);
2260
2261         // FIXME This check should not be needed. Perhaps issue an
2262         // error if it triggers.
2263         Layout const & style = inInset().forcePlainLayout() ?
2264                 bparams.documentClass().plainLayout() : *d->layout_;
2265
2266         if (!force && style.inpreamble)
2267                 return;
2268
2269         bool const allowcust = allowParagraphCustomization();
2270
2271         // Current base font for all inherited font changes, without any
2272         // change caused by an individual character, except for the language:
2273         // It is set to the language of the first character.
2274         // As long as we are in the label, this font is the base font of the
2275         // label. Before the first body character it is set to the base font
2276         // of the body.
2277         Font basefont;
2278
2279         // Maybe we have to create a optional argument.
2280         pos_type body_pos = beginOfBody();
2281         unsigned int column = 0;
2282
2283         if (body_pos > 0) {
2284                 // the optional argument is kept in curly brackets in
2285                 // case it contains a ']'
2286                 os << "[{";
2287                 column += 2;
2288                 basefont = getLabelFont(bparams, outerfont);
2289         } else {
2290                 basefont = getLayoutFont(bparams, outerfont);
2291         }
2292
2293         // Which font is currently active?
2294         Font running_font(basefont);
2295         // Do we have an open font change?
2296         bool open_font = false;
2297
2298         Change runningChange = Change(Change::UNCHANGED);
2299
2300         Encoding const * const prev_encoding = runparams.encoding;
2301
2302         texrow.start(id(), 0);
2303
2304         // if the paragraph is empty, the loop will not be entered at all
2305         if (empty()) {
2306                 if (style.isCommand()) {
2307                         os << '{';
2308                         ++column;
2309                 }
2310                 if (allowcust)
2311                         column += d->startTeXParParams(bparams, os, texrow,
2312                                                     runparams);
2313         }
2314
2315         for (pos_type i = 0; i < size(); ++i) {
2316                 // First char in paragraph or after label?
2317                 if (i == body_pos) {
2318                         if (body_pos > 0) {
2319                                 if (open_font) {
2320                                         column += running_font.latexWriteEndChanges(
2321                                                 os, bparams, runparams,
2322                                                 basefont, basefont);
2323                                         open_font = false;
2324                                 }
2325                                 basefont = getLayoutFont(bparams, outerfont);
2326                                 running_font = basefont;
2327
2328                                 column += Changes::latexMarkChange(os, bparams,
2329                                                 runningChange, Change(Change::UNCHANGED),
2330                                                 runparams);
2331                                 runningChange = Change(Change::UNCHANGED);
2332
2333                                 os << "}] ";
2334                                 column +=3;
2335                         }
2336                         if (style.isCommand()) {
2337                                 os << '{';
2338                                 ++column;
2339                         }
2340
2341                         if (allowcust)
2342                                 column += d->startTeXParParams(bparams, os,
2343                                                             texrow,
2344                                                             runparams);
2345                 }
2346
2347                 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
2348                                                                  : lookupChange(i);
2349
2350                 if (bparams.outputChanges && runningChange != change) {
2351                         if (open_font) {
2352                                 column += running_font.latexWriteEndChanges(
2353                                                 os, bparams, runparams, basefont, basefont);
2354                                 open_font = false;
2355                         }
2356                         basefont = getLayoutFont(bparams, outerfont);
2357                         running_font = basefont;
2358
2359                         column += Changes::latexMarkChange(os, bparams, runningChange,
2360                                                            change, runparams);
2361                         runningChange = change;
2362                 }
2363
2364                 // do not output text which is marked deleted
2365                 // if change tracking output is disabled
2366                 if (!bparams.outputChanges && change.deleted()) {
2367                         continue;
2368                 }
2369
2370                 ++column;
2371
2372                 // Fully instantiated font
2373                 Font const font = getFont(bparams, i, outerfont);
2374
2375                 Font const last_font = running_font;
2376
2377                 // Do we need to close the previous font?
2378                 if (open_font &&
2379                     (font != running_font ||
2380                      font.language() != running_font.language()))
2381                 {
2382                         column += running_font.latexWriteEndChanges(
2383                                         os, bparams, runparams, basefont,
2384                                         (i == body_pos-1) ? basefont : font);
2385                         running_font = basefont;
2386                         open_font = false;
2387                 }
2388
2389                 string const running_lang = runparams.use_polyglossia ?
2390                         running_font.language()->polyglossia() : running_font.language()->babel();
2391                 // close babel's font environment before opening CJK.
2392                 string const lang_end_command = runparams.use_polyglossia ?
2393                         "\\end{$$lang}" : lyxrc.language_command_end;
2394                 if (!running_lang.empty() &&
2395                     font.language()->encoding()->package() == Encoding::CJK) {
2396                                 string end_tag = subst(lang_end_command,
2397                                                         "$$lang",
2398                                                         running_lang);
2399                                 os << from_ascii(end_tag);
2400                                 column += end_tag.length();
2401                 }
2402
2403                 // Switch file encoding if necessary (and allowed)
2404                 if (!runparams.pass_thru && !style.pass_thru &&
2405                     runparams.encoding->package() != Encoding::none &&
2406                     font.language()->encoding()->package() != Encoding::none) {
2407                         pair<bool, int> const enc_switch = switchEncoding(os, bparams,
2408                                         runparams, *(font.language()->encoding()));
2409                         if (enc_switch.first) {
2410                                 column += enc_switch.second;
2411                                 runparams.encoding = font.language()->encoding();
2412                         }
2413                 }
2414
2415                 char_type const c = d->text_[i];
2416
2417                 // Do we need to change font?
2418                 if ((font != running_font ||
2419                      font.language() != running_font.language()) &&
2420                         i != body_pos - 1)
2421                 {
2422                         odocstringstream ods;
2423                         column += font.latexWriteStartChanges(ods, bparams,
2424                                                               runparams, basefont,
2425                                                               last_font);
2426                         running_font = font;
2427                         open_font = true;
2428                         docstring fontchange = ods.str();
2429                         // check whether the fontchange ends with a \\textcolor
2430                         // modifier and the text starts with a space (bug 4473)
2431                         docstring const last_modifier = rsplit(fontchange, '\\');
2432                         if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2433                                 os << fontchange << from_ascii("{}");
2434                         // check if the fontchange ends with a trailing blank
2435                         // (like "\small " (see bug 3382)
2436                         else if (suffixIs(fontchange, ' ') && c == ' ')
2437                                 os << fontchange.substr(0, fontchange.size() - 1)
2438                                    << from_ascii("{}");
2439                         else
2440                                 os << fontchange;
2441                 }
2442
2443                 // FIXME: think about end_pos implementation...
2444                 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2445                         // FIXME: integrate this case in latexSpecialChar
2446                         // Do not print the separation of the optional argument
2447                         // if style.pass_thru is false. This works because
2448                         // latexSpecialChar ignores spaces if
2449                         // style.pass_thru is false.
2450                         if (i != body_pos - 1) {
2451                                 if (d->simpleTeXBlanks(
2452                                                 runparams, os, texrow,
2453                                                 i, column, font, style)) {
2454                                         // A surrogate pair was output. We
2455                                         // must not call latexSpecialChar
2456                                         // in this iteration, since it would output
2457                                         // the combining character again.
2458                                         ++i;
2459                                         continue;
2460                                 }
2461                         }
2462                 }
2463
2464                 OutputParams rp = runparams;
2465                 rp.free_spacing = style.free_spacing;
2466                 rp.local_font = &font;
2467                 rp.intitle = style.intitle;
2468
2469                 // Two major modes:  LaTeX or plain
2470                 // Handle here those cases common to both modes
2471                 // and then split to handle the two modes separately.
2472                 if (c == META_INSET) {
2473                         if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2474                                 d->latexInset(bparams, os,
2475                                                 texrow, rp, running_font,
2476                                                 basefont, outerfont, open_font,
2477                                                 runningChange, style, i, column);
2478                         }
2479                 } else {
2480                         if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2481                                 try {
2482                                         d->latexSpecialChar(os, rp, running_font, runningChange,
2483                                                 style, i, column);
2484                                 } catch (EncodingException & e) {
2485                                 if (runparams.dryrun) {
2486                                         os << "<" << _("LyX Warning: ")
2487                                            << _("uncodable character") << " '";
2488                                         os.put(c);
2489                                         os << "'>";
2490                                 } else {
2491                                         // add location information and throw again.
2492                                         e.par_id = id();
2493                                         e.pos = i;
2494                                         throw(e);
2495                                 }
2496                         }
2497                 }
2498                 }
2499
2500                 // Set the encoding to that returned from latexSpecialChar (see
2501                 // comment for encoding member in OutputParams.h)
2502                 runparams.encoding = rp.encoding;
2503         }
2504
2505         // If we have an open font definition, we have to close it
2506         if (open_font) {
2507 #ifdef FIXED_LANGUAGE_END_DETECTION
2508                 if (next_) {
2509                         running_font.latexWriteEndChanges(os, bparams,
2510                                         runparams, basefont,
2511                                         next_->getFont(bparams, 0, outerfont));
2512                 } else {
2513                         running_font.latexWriteEndChanges(os, bparams,
2514                                         runparams, basefont, basefont);
2515                 }
2516 #else
2517 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2518 //FIXME: there as we start another \selectlanguage with the next paragraph if
2519 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2520                 running_font.latexWriteEndChanges(os, bparams, runparams,
2521                                 basefont, basefont);
2522 #endif
2523         }
2524
2525         column += Changes::latexMarkChange(os, bparams, runningChange,
2526                                            Change(Change::UNCHANGED), runparams);
2527
2528         // Needed if there is an optional argument but no contents.
2529         if (body_pos > 0 && body_pos == size()) {
2530                 os << "}]~";
2531         }
2532
2533         if (allowcust && d->endTeXParParams(bparams, os, texrow, runparams)
2534             && runparams.encoding != prev_encoding) {
2535                 runparams.encoding = prev_encoding;
2536                 if (!runparams.isFullUnicode())
2537                         os << setEncoding(prev_encoding->iconvName());
2538         }
2539
2540         LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2541 }
2542
2543
2544 bool Paragraph::emptyTag() const
2545 {
2546         for (pos_type i = 0; i < size(); ++i) {
2547                 if (Inset const * inset = getInset(i)) {
2548                         InsetCode lyx_code = inset->lyxCode();
2549                         // FIXME testing like that is wrong. What is
2550                         // the intent?
2551                         if (lyx_code != TOC_CODE &&
2552                             lyx_code != INCLUDE_CODE &&
2553                             lyx_code != GRAPHICS_CODE &&
2554                             lyx_code != ERT_CODE &&
2555                             lyx_code != LISTINGS_CODE &&
2556                             lyx_code != FLOAT_CODE &&
2557                             lyx_code != TABULAR_CODE) {
2558                                 return false;
2559                         }
2560                 } else {
2561                         char_type c = d->text_[i];
2562                         if (c != ' ' && c != '\t')
2563                                 return false;
2564                 }
2565         }
2566         return true;
2567 }
2568
2569
2570 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2571         const
2572 {
2573         for (pos_type i = 0; i < size(); ++i) {
2574                 if (Inset const * inset = getInset(i)) {
2575                         InsetCode lyx_code = inset->lyxCode();
2576                         if (lyx_code == LABEL_CODE) {
2577                                 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2578                                 docstring const & id = il->getParam("name");
2579                                 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2580                         }
2581                 }
2582         }
2583         return string();
2584 }
2585
2586
2587 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2588         const
2589 {
2590         pos_type i;
2591         for (i = 0; i < size(); ++i) {
2592                 if (Inset const * inset = getInset(i)) {
2593                         inset->docbook(os, runparams);
2594                 } else {
2595                         char_type c = d->text_[i];
2596                         if (c == ' ')
2597                                 break;
2598                         os << sgml::escapeChar(c);
2599                 }
2600         }
2601         return i;
2602 }
2603
2604
2605 pos_type Paragraph::firstWordLyXHTML(XHTMLStream & xs, OutputParams const & runparams)
2606         const
2607 {
2608         pos_type i;
2609         for (i = 0; i < size(); ++i) {
2610                 if (Inset const * inset = getInset(i)) {
2611                         inset->xhtml(xs, runparams);
2612                 } else {
2613                         char_type c = d->text_[i];
2614                         if (c == ' ')
2615                                 break;
2616                         xs << c;
2617                 }
2618         }
2619         return i;
2620 }
2621
2622
2623 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2624 {
2625         Font font_old;
2626         pos_type size = text_.size();
2627         for (pos_type i = initial; i < size; ++i) {
2628                 Font font = owner_->getFont(buf.params(), i, outerfont);
2629                 if (text_[i] == META_INSET)
2630                         return false;
2631                 if (i != initial && font != font_old)
2632                         return false;
2633                 font_old = font;
2634         }
2635
2636         return true;
2637 }
2638
2639
2640 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2641                                     odocstream & os,
2642                                     OutputParams const & runparams,
2643                                     Font const & outerfont,
2644                                     pos_type initial) const
2645 {
2646         bool emph_flag = false;
2647
2648         Layout const & style = *d->layout_;
2649         FontInfo font_old =
2650                 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2651
2652         if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2653                 os << "]]>";
2654
2655         // parsing main loop
2656         for (pos_type i = initial; i < size(); ++i) {
2657                 Font font = getFont(buf.params(), i, outerfont);
2658
2659                 // handle <emphasis> tag
2660                 if (font_old.emph() != font.fontInfo().emph()) {
2661                         if (font.fontInfo().emph() == FONT_ON) {
2662                                 os << "<emphasis>";
2663                                 emph_flag = true;
2664                         } else if (i != initial) {
2665                                 os << "</emphasis>";
2666                                 emph_flag = false;
2667                         }
2668                 }
2669
2670                 if (Inset const * inset = getInset(i)) {
2671                         inset->docbook(os, runparams);
2672                 } else {
2673                         char_type c = d->text_[i];
2674
2675                         if (style.pass_thru)
2676                                 os.put(c);
2677                         else
2678                                 os << sgml::escapeChar(c);
2679                 }
2680                 font_old = font.fontInfo();
2681         }
2682
2683         if (emph_flag) {
2684                 os << "</emphasis>";
2685         }
2686
2687         if (style.free_spacing)
2688                 os << '\n';
2689         if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2690                 os << "<![CDATA[";
2691 }
2692
2693
2694 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
2695                                     XHTMLStream & xs,
2696                                     OutputParams const & runparams,
2697                                     Font const & outerfont,
2698                                     pos_type initial) const
2699 {
2700         docstring retval;
2701
2702         bool emph_flag = false;
2703         bool bold_flag = false;
2704         string closing_tag;
2705
2706         Layout const & style = *d->layout_;
2707
2708         if (!runparams.for_toc && runparams.html_make_pars) {
2709                 // generate a magic label for this paragraph
2710                 string const attr = "id='" + magicLabel() + "'";
2711                 xs << html::CompTag("a", attr);
2712         }
2713
2714         FontInfo font_old =
2715                 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2716
2717         // parsing main loop
2718         for (pos_type i = initial; i < size(); ++i) {
2719                 // let's not show deleted material in the output
2720                 if (isDeleted(i))
2721                         continue;
2722
2723                 Font font = getFont(buf.params(), i, outerfont);
2724
2725                 // emphasis
2726                 if (font_old.emph() != font.fontInfo().emph()) {
2727                         if (font.fontInfo().emph() == FONT_ON) {
2728                                 xs << html::StartTag("em");
2729                                 emph_flag = true;
2730                         } else if (emph_flag && i != initial) {
2731                                 xs << html::EndTag("em");
2732                                 emph_flag = false;
2733                         }
2734                 }
2735                 // bold
2736                 if (font_old.series() != font.fontInfo().series()) {
2737                         if (font.fontInfo().series() == BOLD_SERIES) {
2738                                 xs << html::StartTag("strong");
2739                                 bold_flag = true;
2740                         } else if (bold_flag && i != initial) {
2741                                 xs << html::EndTag("strong");
2742                                 bold_flag = false;
2743                         }
2744                 }
2745                 // FIXME XHTML
2746                 // Other such tags? What about the other text ranges?
2747
2748                 Inset const * inset = getInset(i);
2749                 if (inset) {
2750                         if (!runparams.for_toc || inset->isInToc()) {
2751                                 OutputParams np = runparams;
2752                                 if (!inset->getLayout().htmlisblock())
2753                                         np.html_in_par = true;
2754                                 retval += inset->xhtml(xs, np);
2755                         }
2756                 } else {
2757                         char_type c = d->text_[i];
2758
2759                         if (style.pass_thru)
2760                                 xs << c;
2761                         else if (c == '-') {
2762                                 docstring str;
2763                                 int j = i + 1;
2764                                 if (j < size() && d->text_[j] == '-') {
2765                                         j += 1;
2766                                         if (j < size() && d->text_[j] == '-') {
2767                                                 str += from_ascii("&mdash;");
2768                                                 i += 2;
2769                                         } else {
2770                                                 str += from_ascii("&ndash;");
2771                                                 i += 1;
2772                                         }
2773                                 }
2774                                 else
2775                                         str += c;
2776                                 // We don't want to escape the entities. Note that
2777                                 // it is safe to do this, since str can otherwise
2778                                 // only be "-". E.g., it can't be "<".
2779                                 xs << XHTMLStream::ESCAPE_NONE << str;
2780                         } else
2781                                 xs << c;
2782                 }
2783                 font_old = font.fontInfo();
2784         }
2785
2786         xs.closeFontTags();
2787         return retval;
2788 }
2789
2790
2791 bool Paragraph::isHfill(pos_type pos) const
2792 {
2793         Inset const * inset = getInset(pos);
2794         return inset && (inset->lyxCode() == SPACE_CODE &&
2795                          inset->isStretchableSpace());
2796 }
2797
2798
2799 bool Paragraph::isNewline(pos_type pos) const
2800 {
2801         Inset const * inset = getInset(pos);
2802         return inset && inset->lyxCode() == NEWLINE_CODE;
2803 }
2804
2805
2806 bool Paragraph::isLineSeparator(pos_type pos) const
2807 {
2808         char_type const c = d->text_[pos];
2809         if (isLineSeparatorChar(c))
2810                 return true;
2811         Inset const * inset = getInset(pos);
2812         return inset && inset->isLineSeparator();
2813 }
2814
2815
2816 bool Paragraph::isWordSeparator(pos_type pos) const
2817 {
2818         if (Inset const * inset = getInset(pos))
2819                 return !inset->isLetter();
2820         char_type const c = d->text_[pos];
2821         // We want to pass the ' and escape chars to the spellchecker
2822         static docstring const quote = from_utf8(lyxrc.spellchecker_esc_chars + '\'');
2823         return (!isLetterChar(c) && !isDigitASCII(c) && !contains(quote, c))
2824                 || pos == size();
2825 }
2826
2827
2828 bool Paragraph::isChar(pos_type pos) const
2829 {
2830         if (Inset const * inset = getInset(pos))
2831                 return inset->isChar();
2832         char_type const c = d->text_[pos];
2833         return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
2834 }
2835
2836
2837 bool Paragraph::isSpace(pos_type pos) const
2838 {
2839         if (Inset const * inset = getInset(pos))
2840                 return inset->isSpace();
2841         char_type const c = d->text_[pos];
2842         return lyx::isSpace(c);
2843 }
2844
2845
2846 Language const *
2847 Paragraph::getParLanguage(BufferParams const & bparams) const
2848 {
2849         if (!empty())
2850                 return getFirstFontSettings(bparams).language();
2851         // FIXME: we should check the prev par as well (Lgb)
2852         return bparams.language;
2853 }
2854
2855
2856 bool Paragraph::isRTL(BufferParams const & bparams) const
2857 {
2858         return lyxrc.rtl_support
2859                 && getParLanguage(bparams)->rightToLeft()
2860                 && !inInset().getLayout().forceLTR();
2861 }
2862
2863
2864 void Paragraph::changeLanguage(BufferParams const & bparams,
2865                                Language const * from, Language const * to)
2866 {
2867         // change language including dummy font change at the end
2868         for (pos_type i = 0; i <= size(); ++i) {
2869                 Font font = getFontSettings(bparams, i);
2870                 if (font.language() == from) {
2871                         font.setLanguage(to);
2872                         setFont(i, font);
2873                 }
2874         }
2875         d->requestSpellCheck(size());
2876 }
2877
2878
2879 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2880 {
2881         Language const * doc_language = bparams.language;
2882         FontList::const_iterator cit = d->fontlist_.begin();
2883         FontList::const_iterator end = d->fontlist_.end();
2884
2885         for (; cit != end; ++cit)
2886                 if (cit->font().language() != ignore_language &&
2887                     cit->font().language() != latex_language &&
2888                     cit->font().language() != doc_language)
2889                         return true;
2890         return false;
2891 }
2892
2893
2894 void Paragraph::getLanguages(std::set<Language const *> & languages) const
2895 {
2896         FontList::const_iterator cit = d->fontlist_.begin();
2897         FontList::const_iterator end = d->fontlist_.end();
2898
2899         for (; cit != end; ++cit) {
2900                 Language const * lang = cit->font().language();
2901                 if (lang != ignore_language &&
2902                     lang != latex_language)
2903                         languages.insert(lang);
2904         }
2905 }
2906
2907
2908 docstring Paragraph::asString(int options) const
2909 {
2910         return asString(0, size(), options);
2911 }
2912
2913
2914 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
2915 {
2916         odocstringstream os;
2917
2918         if (beg == 0
2919             && options & AS_STR_LABEL
2920             && !d->params_.labelString().empty())
2921                 os << d->params_.labelString() << ' ';
2922
2923         for (pos_type i = beg; i < end; ++i) {
2924                 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
2925                         continue;
2926                 char_type const c = d->text_[i];
2927                 if (isPrintable(c) || c == '\t'
2928                     || (c == '\n' && (options & AS_STR_NEWLINES)))
2929                         os.put(c);
2930                 else if (c == META_INSET && (options & AS_STR_INSETS)) {
2931                         getInset(i)->toString(os);
2932                         if (getInset(i)->asInsetMath())
2933                                 os << " ";
2934                 }
2935         }
2936
2937         return os.str();
2938 }
2939
2940
2941 docstring Paragraph::stringify(pos_type beg, pos_type end, int options, OutputParams & runparams) const
2942 {
2943         odocstringstream os;
2944
2945         if (beg == 0
2946                 && options & AS_STR_LABEL
2947                 && !d->params_.labelString().empty())
2948                 os << d->params_.labelString() << ' ';
2949
2950         for (pos_type i = beg; i < end; ++i) {
2951                 char_type const c = d->text_[i];
2952                 if (isPrintable(c) || c == '\t'
2953                     || (c == '\n' && (options & AS_STR_NEWLINES)))
2954                         os.put(c);
2955                 else if (c == META_INSET && (options & AS_STR_INSETS)) {
2956                         getInset(i)->plaintext(os, runparams);
2957                 }
2958         }
2959
2960         return os.str();
2961 }
2962
2963
2964 void Paragraph::setInsetOwner(Inset const * inset)
2965 {
2966         d->inset_owner_ = inset;
2967 }
2968
2969
2970 int Paragraph::id() const
2971 {
2972         return d->id_;
2973 }
2974
2975
2976 void Paragraph::setId(int id)
2977 {
2978         d->id_ = id;
2979 }
2980
2981
2982 Layout const & Paragraph::layout() const
2983 {
2984         return *d->layout_;
2985 }
2986
2987
2988 void Paragraph::setLayout(Layout const & layout)
2989 {
2990         d->layout_ = &layout;
2991 }
2992
2993
2994 void Paragraph::setDefaultLayout(DocumentClass const & tc)
2995 {
2996         setLayout(tc.defaultLayout());
2997 }
2998
2999
3000 void Paragraph::setPlainLayout(DocumentClass const & tc)
3001 {
3002         setLayout(tc.plainLayout());
3003 }
3004
3005
3006 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
3007 {
3008         if (usePlainLayout())
3009                 setPlainLayout(tclass);
3010         else
3011                 setDefaultLayout(tclass);
3012 }
3013
3014
3015 Inset const & Paragraph::inInset() const
3016 {
3017         LASSERT(d->inset_owner_, throw ExceptionMessage(BufferException,
3018                 _("Memory problem"), _("Paragraph not properly initialized")));
3019         return *d->inset_owner_;
3020 }
3021
3022
3023 ParagraphParameters & Paragraph::params()
3024 {
3025         return d->params_;
3026 }
3027
3028
3029 ParagraphParameters const & Paragraph::params() const
3030 {
3031         return d->params_;
3032 }
3033
3034
3035 bool Paragraph::isFreeSpacing() const
3036 {
3037         if (d->layout_->free_spacing)
3038                 return true;
3039         return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
3040 }
3041
3042
3043 bool Paragraph::allowEmpty() const
3044 {
3045         if (d->layout_->keepempty)
3046                 return true;
3047         return d->inset_owner_ && d->inset_owner_->allowEmpty();
3048 }
3049
3050
3051 char_type Paragraph::transformChar(char_type c, pos_type pos) const
3052 {
3053         if (!Encodings::isArabicChar(c))
3054                 return c;
3055
3056         char_type prev_char = ' ';
3057         char_type next_char = ' ';
3058
3059         for (pos_type i = pos - 1; i >= 0; --i) {
3060                 char_type const par_char = d->text_[i];
3061                 if (!Encodings::isArabicComposeChar(par_char)) {
3062                         prev_char = par_char;
3063                         break;
3064                 }
3065         }
3066
3067         for (pos_type i = pos + 1, end = size(); i < end; ++i) {
3068                 char_type const par_char = d->text_[i];
3069                 if (!Encodings::isArabicComposeChar(par_char)) {
3070                         next_char = par_char;
3071                         break;
3072                 }
3073         }
3074
3075         if (Encodings::isArabicChar(next_char)) {
3076                 if (Encodings::isArabicChar(prev_char) &&
3077                         !Encodings::isArabicSpecialChar(prev_char))
3078                         return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
3079                 else
3080                         return Encodings::transformChar(c, Encodings::FORM_INITIAL);
3081         } else {
3082                 if (Encodings::isArabicChar(prev_char) &&
3083                         !Encodings::isArabicSpecialChar(prev_char))
3084                         return Encodings::transformChar(c, Encodings::FORM_FINAL);
3085                 else
3086                         return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
3087         }
3088 }
3089
3090
3091 int Paragraph::checkBiblio(Buffer const & buffer)
3092 {
3093         // FIXME From JS:
3094         // This is getting more and more a mess. ...We really should clean
3095         // up this bibitem issue for 1.6.
3096
3097         // Add bibitem insets if necessary
3098         if (d->layout_->labeltype != LABEL_BIBLIO)
3099                 return 0;
3100
3101         bool hasbibitem = !d->insetlist_.empty()
3102                 // Insist on it being in pos 0
3103                 && d->text_[0] == META_INSET
3104                 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
3105
3106         bool track_changes = buffer.params().trackChanges;
3107
3108         docstring oldkey;
3109         docstring oldlabel;
3110
3111         // remove a bibitem in pos != 0
3112         // restore it later in pos 0 if necessary
3113         // (e.g. if a user inserts contents _before_ the item)
3114         // we're assuming there's only one of these, which there
3115         // should be.
3116         int erasedInsetPosition = -1;
3117         InsetList::iterator it = d->insetlist_.begin();
3118         InsetList::iterator end = d->insetlist_.end();
3119         for (; it != end; ++it)
3120                 if (it->inset->lyxCode() == BIBITEM_CODE
3121                       && it->pos > 0) {
3122                         InsetCommand * olditem = it->inset->asInsetCommand();
3123                         oldkey = olditem->getParam("key");
3124                         oldlabel = olditem->getParam("label");
3125                         erasedInsetPosition = it->pos;
3126                         eraseChar(erasedInsetPosition, track_changes);
3127                         break;
3128         }
3129
3130         // There was an InsetBibitem at the beginning, and we didn't
3131         // have to erase one.
3132         if (hasbibitem && erasedInsetPosition < 0)
3133                         return 0;
3134
3135         // There was an InsetBibitem at the beginning and we did have to
3136         // erase one. So we give its properties to the beginning inset.
3137         if (hasbibitem) {
3138                 InsetCommand * inset = d->insetlist_.begin()->inset->asInsetCommand();
3139                 if (!oldkey.empty())
3140                         inset->setParam("key", oldkey);
3141                 inset->setParam("label", oldlabel);
3142                 return -erasedInsetPosition;
3143         }
3144
3145         // There was no inset at the beginning, so we need to create one with
3146         // the key and label of the one we erased.
3147         InsetBibitem * inset =
3148                 new InsetBibitem(const_cast<Buffer *>(&buffer), InsetCommandParams(BIBITEM_CODE));
3149         // restore values of previously deleted item in this par.
3150         if (!oldkey.empty())
3151                 inset->setParam("key", oldkey);
3152         inset->setParam("label", oldlabel);
3153         insertInset(0, inset,
3154                     Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
3155
3156         return 1;
3157 }
3158
3159
3160 void Paragraph::checkAuthors(AuthorList const & authorList)
3161 {
3162         d->changes_.checkAuthors(authorList);
3163 }
3164
3165
3166 bool Paragraph::isChanged(pos_type pos) const
3167 {
3168         return lookupChange(pos).changed();
3169 }
3170
3171
3172 bool Paragraph::isInserted(pos_type pos) const
3173 {
3174         return lookupChange(pos).inserted();
3175 }
3176
3177
3178 bool Paragraph::isDeleted(pos_type pos) const
3179 {
3180         return lookupChange(pos).deleted();
3181 }
3182
3183
3184 InsetList const & Paragraph::insetList() const
3185 {
3186         return d->insetlist_;
3187 }
3188
3189
3190 void Paragraph::setBuffer(Buffer & b)
3191 {
3192         d->insetlist_.setBuffer(b);
3193 }
3194
3195
3196 Inset * Paragraph::releaseInset(pos_type pos)
3197 {
3198         Inset * inset = d->insetlist_.release(pos);
3199         /// does not honour change tracking!
3200         eraseChar(pos, false);
3201         return inset;
3202 }
3203
3204
3205 Inset * Paragraph::getInset(pos_type pos)
3206 {
3207         return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3208                  ? d->insetlist_.get(pos) : 0;
3209 }
3210
3211
3212 Inset const * Paragraph::getInset(pos_type pos) const
3213 {
3214         return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3215                  ? d->insetlist_.get(pos) : 0;
3216 }
3217
3218
3219 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
3220                 pos_type & right, TextCase action)
3221 {
3222         // process sequences of modified characters; in change
3223         // tracking mode, this approach results in much better
3224         // usability than changing case on a char-by-char basis
3225         docstring changes;
3226
3227         bool const trackChanges = bparams.trackChanges;
3228
3229         bool capitalize = true;
3230
3231         for (; pos < right; ++pos) {
3232                 char_type oldChar = d->text_[pos];
3233                 char_type newChar = oldChar;
3234
3235                 // ignore insets and don't play with deleted text!
3236                 if (oldChar != META_INSET && !isDeleted(pos)) {
3237                         switch (action) {
3238                                 case text_lowercase:
3239                                         newChar = lowercase(oldChar);
3240                                         break;
3241                                 case text_capitalization:
3242                                         if (capitalize) {
3243                                                 newChar = uppercase(oldChar);
3244                                                 capitalize = false;
3245                                         }
3246                                         break;
3247                                 case text_uppercase:
3248                                         newChar = uppercase(oldChar);
3249                                         break;
3250                         }
3251                 }
3252
3253                 if (isWordSeparator(pos) || isDeleted(pos)) {
3254                         // permit capitalization again
3255                         capitalize = true;
3256                 }
3257
3258                 if (oldChar != newChar) {
3259                         changes += newChar;
3260                         if (pos != right - 1)
3261                                 continue;
3262                         // step behind the changing area
3263                         pos++;
3264                 }
3265
3266                 int erasePos = pos - changes.size();
3267                 for (size_t i = 0; i < changes.size(); i++) {
3268                         insertChar(pos, changes[i],
3269                                    getFontSettings(bparams,
3270                                                    erasePos),
3271                                    trackChanges);
3272                         if (!eraseChar(erasePos, trackChanges)) {
3273                                 ++erasePos;
3274                                 ++pos; // advance
3275                                 ++right; // expand selection
3276                         }
3277                 }
3278                 changes.clear();
3279         }
3280 }
3281
3282
3283 int Paragraph::find(docstring const & str, bool cs, bool mw,
3284                 pos_type start_pos, bool del) const
3285 {
3286         pos_type pos = start_pos;
3287         int const strsize = str.length();
3288         int i = 0;
3289         pos_type const parsize = d->text_.size();
3290         for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
3291                 // Ignore ligature break and hyphenation chars while searching
3292                 while (pos < parsize - 1 && isInset(pos)) {
3293                         const InsetSpecialChar *isc = dynamic_cast<const InsetSpecialChar*>(getInset(pos));
3294                         if (isc == 0
3295                             || (isc->kind() != InsetSpecialChar::HYPHENATION
3296                                 && isc->kind() != InsetSpecialChar::LIGATURE_BREAK))
3297                                 break;
3298                         pos++;
3299                 }
3300                 if (cs && str[i] != d->text_[pos])
3301                         break;
3302                 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
3303                         break;
3304                 if (!del && isDeleted(pos))
3305                         break;
3306         }
3307
3308         if (i != strsize)
3309                 return 0;
3310
3311         // if necessary, check whether string matches word
3312         if (mw) {
3313                 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
3314                         return 0;
3315                 if (pos < parsize
3316                         && !isWordSeparator(pos))
3317                         return 0;
3318         }
3319
3320         return pos - start_pos;
3321 }
3322
3323
3324 char_type Paragraph::getChar(pos_type pos) const
3325 {
3326         return d->text_[pos];
3327 }
3328
3329
3330 pos_type Paragraph::size() const
3331 {
3332         return d->text_.size();
3333 }
3334
3335
3336 bool Paragraph::empty() const
3337 {
3338         return d->text_.empty();
3339 }
3340
3341
3342 bool Paragraph::isInset(pos_type pos) const
3343 {
3344         return d->text_[pos] == META_INSET;
3345 }
3346
3347
3348 bool Paragraph::isSeparator(pos_type pos) const
3349 {
3350         //FIXME: Are we sure this can be the only separator?
3351         return d->text_[pos] == ' ';
3352 }
3353
3354
3355 void Paragraph::deregisterWords()
3356 {
3357         Private::LangWordsMap::const_iterator itl = d->words_.begin();
3358         Private::LangWordsMap::const_iterator ite = d->words_.end();
3359         for (; itl != ite; ++itl) {
3360                 WordList * wl = theWordList(itl->first);
3361                 Private::Words::const_iterator it = (itl->second).begin();
3362                 Private::Words::const_iterator et = (itl->second).end();
3363                 for (; it != et; ++it)
3364                         wl->remove(*it);
3365         }
3366         d->words_.clear();
3367 }
3368
3369
3370 void Paragraph::locateWord(pos_type & from, pos_type & to,
3371         word_location const loc) const
3372 {
3373         switch (loc) {
3374         case WHOLE_WORD_STRICT:
3375                 if (from == 0 || from == size()
3376                     || isWordSeparator(from)
3377                     || isWordSeparator(from - 1)) {
3378                         to = from;
3379                         return;
3380                 }
3381                 // no break here, we go to the next
3382
3383         case WHOLE_WORD:
3384                 // If we are already at the beginning of a word, do nothing
3385                 if (!from || isWordSeparator(from - 1))
3386                         break;
3387                 // no break here, we go to the next
3388
3389         case PREVIOUS_WORD:
3390                 // always move the cursor to the beginning of previous word
3391                 while (from && !isWordSeparator(from - 1))
3392                         --from;
3393                 break;
3394         case NEXT_WORD:
3395                 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
3396                 break;
3397         case PARTIAL_WORD:
3398                 // no need to move the 'from' cursor
3399                 break;
3400         }
3401         to = from;
3402         while (to < size() && !isWordSeparator(to))
3403                 ++to;
3404 }
3405
3406
3407 void Paragraph::collectWords()
3408 {
3409         // This is the value that needs to be exposed in the preferences
3410         // to resolve bug #6760.
3411         static int minlength = 6;
3412         pos_type n = size();
3413         for (pos_type pos = 0; pos < n; ++pos) {
3414                 if (isWordSeparator(pos))
3415                         continue;
3416                 pos_type from = pos;
3417                 locateWord(from, pos, WHOLE_WORD);
3418                 if (pos - from >= minlength) {
3419                         docstring word = asString(from, pos, AS_STR_NONE);
3420                         FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
3421                         if (cit == d->fontlist_.end())
3422                                 return;
3423                         Language const * lang = cit->font().language();
3424                         d->words_[*lang].insert(word);
3425                 }
3426         }
3427 }
3428
3429
3430 void Paragraph::registerWords()
3431 {
3432         Private::LangWordsMap::const_iterator itl = d->words_.begin();
3433         Private::LangWordsMap::const_iterator ite = d->words_.end();
3434         for (; itl != ite; ++itl) {
3435                 WordList * wl = theWordList(itl->first);
3436                 Private::Words::const_iterator it = (itl->second).begin();
3437                 Private::Words::const_iterator et = (itl->second).end();
3438                 for (; it != et; ++it)
3439                         wl->insert(*it);
3440         }
3441 }
3442
3443
3444 void Paragraph::updateWords()
3445 {
3446         deregisterWords();
3447         collectWords();
3448         registerWords();
3449 }
3450
3451
3452 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
3453 {
3454         SkipPositionsIterator begin = skips.begin();
3455         SkipPositions::iterator end = skips.end();
3456         if (pos > 0 && begin < end) {
3457                 --end;
3458                 if (end->last == pos - 1) {
3459                         end->last = pos;
3460                         return;
3461                 }
3462         }
3463         skips.insert(end, FontSpan(pos, pos));
3464 }
3465
3466
3467 Language * Paragraph::Private::locateSpellRange(
3468         pos_type & from, pos_type & to,
3469         SkipPositions & skips) const
3470 {
3471         // skip leading white space
3472         while (from < to && owner_->isWordSeparator(from))
3473                 ++from;
3474         // don't check empty range
3475         if (from >= to)
3476                 return 0;
3477         // get current language
3478         Language * lang = getSpellLanguage(from);
3479         pos_type last = from;
3480         bool samelang = true;
3481         bool sameinset = true;
3482         while (last < to && samelang && sameinset) {
3483                 // hop to end of word
3484                 while (last < to && !owner_->isWordSeparator(last)) {
3485                         if (owner_->getInset(last)) {
3486                                 appendSkipPosition(skips, last);
3487                         } else if (owner_->isDeleted(last)) {
3488                                 appendSkipPosition(skips, last);
3489                         }
3490                         ++last;
3491                 }
3492                 // hop to next word while checking for insets
3493                 while (sameinset && last < to && owner_->isWordSeparator(last)) {
3494                         if (Inset const * inset = owner_->getInset(last))
3495                                 sameinset = inset->isChar() && inset->isLetter();
3496                         if (sameinset && owner_->isDeleted(last)) {
3497                                 appendSkipPosition(skips, last);
3498                         }
3499                         if (sameinset)
3500                                 last++;
3501                 }
3502                 if (sameinset && last < to) {
3503                         // now check for language change
3504                         samelang = lang == getSpellLanguage(last);
3505                 }
3506         }
3507         // if language change detected backstep is needed
3508         if (!samelang)
3509                 --last;
3510         to = last;
3511         return lang;
3512 }
3513
3514
3515 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
3516 {
3517         Language * lang =
3518                 const_cast<Language *>(owner_->getFontSettings(
3519                         inset_owner_->buffer().params(), from).language());
3520         if (lang == inset_owner_->buffer().params().language
3521                 && !lyxrc.spellchecker_alt_lang.empty()) {
3522                 string lang_code;
3523                 string const lang_variety =
3524                         split(lyxrc.spellchecker_alt_lang, lang_code, '-');
3525                 lang->setCode(lang_code);
3526                 lang->setVariety(lang_variety);
3527         }
3528         return lang;
3529 }
3530
3531
3532 void Paragraph::requestSpellCheck(pos_type pos)
3533 {
3534         d->requestSpellCheck(pos == -1 ? size() : pos);
3535 }
3536
3537
3538 bool Paragraph::needsSpellCheck() const
3539 {
3540         SpellChecker::ChangeNumber speller_change_number = 0;
3541         if (theSpellChecker())
3542                 speller_change_number = theSpellChecker()->changeNumber();
3543         if (speller_change_number > d->speller_state_.currentChangeNumber()) {
3544                 d->speller_state_.needsCompleteRefresh(speller_change_number);
3545         }
3546         return d->needsSpellCheck();
3547 }
3548
3549
3550 bool Paragraph::Private::ignoreWord(docstring const & word) const
3551 {
3552         // Ignore words with digits
3553         // FIXME: make this customizable
3554         // (note that some checkers ignore words with digits by default)
3555         docstring::const_iterator cit = word.begin();
3556         docstring::const_iterator const end = word.end();
3557         for (; cit != end; ++cit) {
3558                 if (isNumber((*cit)))
3559                         return true;
3560         }
3561         return false;
3562 }
3563
3564
3565 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
3566         WordLangTuple & wl, docstring_list & suggestions,
3567         bool do_suggestion, bool check_learned) const
3568 {
3569         SpellChecker::Result result = SpellChecker::WORD_OK;
3570         SpellChecker * speller = theSpellChecker();
3571         if (!speller)
3572                 return result;
3573
3574         if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
3575                 return result;
3576
3577         locateWord(from, to, WHOLE_WORD);
3578         if (from == to || from >= size())
3579                 return result;
3580
3581         docstring word = asString(from, to, AS_STR_INSETS + AS_STR_SKIPDELETE);
3582         Language * lang = d->getSpellLanguage(from);
3583
3584         wl = WordLangTuple(word, lang);
3585
3586         if (!word.size())
3587                 return result;
3588
3589         if (needsSpellCheck() || check_learned) {
3590                 if (!d->ignoreWord(word)) {
3591                         bool const trailing_dot = to < size() && d->text_[to] == '.';
3592                         result = speller->check(wl);
3593                         if (SpellChecker::misspelled(result) && trailing_dot) {
3594                                 wl = WordLangTuple(word.append(from_ascii(".")), lang);
3595                                 result = speller->check(wl);
3596                                 if (!SpellChecker::misspelled(result)) {
3597                                         LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
3598                                            word << "\" [" <<
3599                                            from << ".." << to << "]");
3600                                 }
3601                         }
3602                 }
3603                 d->setMisspelled(from, to, result);
3604         } else {
3605                 result = d->speller_state_.getState(from);
3606         }
3607
3608         bool const misspelled_ = SpellChecker::misspelled(result) ;
3609         if (misspelled_ && do_suggestion)
3610                 speller->suggest(wl, suggestions);
3611         else if (misspelled_)
3612                 LYXERR(Debug::GUI, "misspelled word: \"" <<
3613                            word << "\" [" <<
3614                            from << ".." << to << "]");
3615         else
3616                 suggestions.clear();
3617
3618         return result;
3619 }
3620
3621
3622 void Paragraph::Private::markMisspelledWords(
3623         pos_type const & first, pos_type const & last,
3624         SpellChecker::Result result,
3625         docstring const & word,
3626         SkipPositions const & skips)
3627 {
3628         if (!SpellChecker::misspelled(result)) {
3629                 setMisspelled(first, last, SpellChecker::WORD_OK);
3630                 return;
3631         }
3632         int snext = first;
3633         SpellChecker * speller = theSpellChecker();
3634         // locate and enumerate the error positions
3635         int nerrors = speller->numMisspelledWords();
3636         int numskipped = 0;
3637         SkipPositionsIterator it = skips.begin();
3638         SkipPositionsIterator et = skips.end();
3639         for (int index = 0; index < nerrors; ++index) {
3640                 int wstart;
3641                 int wlen = 0;
3642                 speller->misspelledWord(index, wstart, wlen);
3643                 /// should not happen if speller supports range checks
3644                 if (!wlen) continue;
3645                 docstring const misspelled = word.substr(wstart, wlen);
3646                 wstart += first + numskipped;
3647                 if (snext < wstart) {
3648                         /// mark the range of correct spelling
3649                         numskipped += countSkips(it, et, wstart);
3650                         setMisspelled(snext,
3651                                 wstart - 1, SpellChecker::WORD_OK);
3652                 }
3653                 snext = wstart + wlen;
3654                 numskipped += countSkips(it, et, snext);
3655                 /// mark the range of misspelling
3656                 setMisspelled(wstart, snext, result);
3657                 LYXERR(Debug::GUI, "misspelled word: \"" <<
3658                            misspelled << "\" [" <<
3659                            wstart << ".." << (snext-1) << "]");
3660                 ++snext;
3661         }
3662         if (snext <= last) {
3663                 /// mark the range of correct spelling at end
3664                 setMisspelled(snext, last, SpellChecker::WORD_OK);
3665         }
3666 }
3667
3668
3669 void Paragraph::spellCheck() const
3670 {
3671         SpellChecker * speller = theSpellChecker();
3672         if (!speller || !size() ||!needsSpellCheck())
3673                 return;
3674         pos_type start;
3675         pos_type endpos;
3676         d->rangeOfSpellCheck(start, endpos);
3677         if (speller->canCheckParagraph()) {
3678                 // loop until we leave the range
3679                 for (pos_type first = start; first < endpos; ) {
3680                         pos_type last = endpos;
3681                         Private::SkipPositions skips;
3682                         Language * lang = d->locateSpellRange(first, last, skips);
3683                         if (first >= endpos)
3684                                 break;
3685                         // start the spell checker on the unit of meaning
3686                         docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
3687                         WordLangTuple wl = WordLangTuple(word, lang);
3688                         SpellChecker::Result result = word.size() ?
3689                                 speller->check(wl) : SpellChecker::WORD_OK;
3690                         d->markMisspelledWords(first, last, result, word, skips);
3691                         first = ++last;
3692                 }
3693         } else {
3694                 static docstring_list suggestions;
3695                 pos_type to = endpos;
3696                 while (start < endpos) {
3697                         WordLangTuple wl;
3698                         spellCheck(start, to, wl, suggestions, false);
3699                         start = to + 1;
3700                 }
3701         }
3702         d->readySpellCheck();
3703 }
3704
3705
3706 bool Paragraph::isMisspelled(pos_type pos) const
3707 {
3708         return SpellChecker::misspelled(d->speller_state_.getState(pos));
3709 }
3710
3711
3712 string Paragraph::magicLabel() const
3713 {
3714         stringstream ss;
3715         ss << "magicparlabel-" << id();
3716         return ss.str();
3717 }
3718
3719
3720 } // namespace lyx