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