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