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