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