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