]> git.lyx.org Git - lyx.git/blob - src/Paragraph.cpp
continue spellchecking after "replace all"
[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 Jean-Marc Lasgouttes
9  * \author Angus Leeming
10  * \author John Levon
11  * \author André Pönitz
12  * \author Dekel Tsur
13  * \author Jürgen Vigna
14  *
15  * Full author contact details are available in file CREDITS.
16  */
17
18 #include <config.h>
19
20 #include "Paragraph.h"
21
22 #include "LayoutFile.h"
23 #include "Buffer.h"
24 #include "BufferParams.h"
25 #include "Changes.h"
26 #include "Counters.h"
27 #include "Encoding.h"
28 #include "InsetList.h"
29 #include "Language.h"
30 #include "LaTeXFeatures.h"
31 #include "Layout.h"
32 #include "Length.h"
33 #include "Font.h"
34 #include "FontList.h"
35 #include "LyXRC.h"
36 #include "OutputParams.h"
37 #include "output_latex.h"
38 #include "output_xhtml.h"
39 #include "paragraph_funcs.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 "VSpace.h"
47 #include "WordLangTuple.h"
48 #include "WordList.h"
49
50 #include "frontends/alert.h"
51
52 #include "insets/InsetBibitem.h"
53 #include "insets/InsetLabel.h"
54
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/Messages.h"
62 #include "support/textutils.h"
63
64 #include <sstream>
65 #include <vector>
66
67 using namespace std;
68 using namespace lyx::support;
69
70 namespace lyx {
71
72 namespace {
73 /// Inset identifier (above 0x10ffff, for ucs-4)
74 char_type const META_INSET = 0x200001;
75 };
76
77 /////////////////////////////////////////////////////////////////////
78 //
79 // Paragraph::Private
80 //
81 /////////////////////////////////////////////////////////////////////
82
83 class Paragraph::Private
84 {
85 public:
86         ///
87         Private(Paragraph * owner, Layout const & layout);
88         /// "Copy constructor"
89         Private(Private const &, Paragraph * owner);
90         /// Copy constructor from \p beg  to \p end
91         Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
92
93         ///
94         void insertChar(pos_type pos, char_type c, Change const & change);
95
96         /// Output the surrogate pair formed by \p c and \p next to \p os.
97         /// \return the number of characters written.
98         int latexSurrogatePair(odocstream & os, char_type c, char_type next,
99                                Encoding const &);
100
101         /// Output a space in appropriate formatting (or a surrogate pair
102         /// if the next character is a combining character).
103         /// \return whether a surrogate pair was output.
104         bool simpleTeXBlanks(OutputParams const &,
105                              odocstream &, TexRow & texrow,
106                              pos_type i,
107                              unsigned int & column,
108                              Font const & font,
109                              Layout const & style);
110
111         /// Output consecutive unicode chars, belonging to the same script as
112         /// specified by the latex macro \p ltx, to \p os starting from \p i.
113         /// \return the number of characters written.
114         int writeScriptChars(odocstream & os, docstring const & ltx,
115                            Change const &, Encoding const &, pos_type & i);
116
117         /// This could go to ParagraphParameters if we want to.
118         int startTeXParParams(BufferParams const &, odocstream &, TexRow &,
119                               OutputParams const &) const;
120
121         /// This could go to ParagraphParameters if we want to.
122         int endTeXParParams(BufferParams const &, odocstream &, TexRow &,
123                             OutputParams const &) const;
124
125         ///
126         void latexInset(BufferParams const &,
127                                    odocstream &,
128                                    TexRow & texrow, OutputParams &,
129                                    Font & running_font,
130                                    Font & basefont,
131                                    Font const & outerfont,
132                                    bool & open_font,
133                                    Change & running_change,
134                                    Layout const & style,
135                                    pos_type & i,
136                                    unsigned int & column);
137
138         ///
139         void latexSpecialChar(
140                                    odocstream & os,
141                                    OutputParams const & runparams,
142                                    Font const & running_font,
143                                    Change const & running_change,
144                                    Layout const & style,
145                                    pos_type & i,
146                                    unsigned int & column);
147
148         ///
149         bool latexSpecialT1(
150                 char_type const c,
151                 odocstream & os,
152                 pos_type i,
153                 unsigned int & column);
154         ///
155         bool latexSpecialTypewriter(
156                 char_type const c,
157                 odocstream & os,
158                 pos_type i,
159                 unsigned int & column);
160         ///
161         bool latexSpecialPhrase(
162                 odocstream & os,
163                 pos_type & i,
164                 unsigned int & column,
165                 OutputParams const & runparams);
166
167         ///
168         void validate(LaTeXFeatures & features,
169                       Layout const & layout) const;
170
171         /// Checks if the paragraph contains only text and no inset or font change.
172         bool onlyText(Buffer const & buf, Font const & outerfont,
173                       pos_type initial) const;
174
175         /// match a string against a particular point in the paragraph
176         bool isTextAt(string const & str, pos_type pos) const;
177         
178         /// Which Paragraph owns us?
179         Paragraph * owner_;
180
181         /// In which Inset?
182         Inset const * inset_owner_;
183
184         ///
185         FontList fontlist_;
186
187         ///
188         unsigned int id_;
189         ///
190         static unsigned int paragraph_id;
191         ///
192         ParagraphParameters params_;
193
194         /// for recording and looking up changes
195         Changes changes_;
196
197         ///
198         InsetList insetlist_;
199
200         /// end of label
201         pos_type begin_of_body_;
202
203         typedef docstring TextContainer;
204         ///
205         TextContainer text_;
206         
207         typedef std::set<docstring> Words;
208         ///
209         Words words_;
210         ///
211         Layout const * layout_;
212 };
213
214
215 // Initialization of the counter for the paragraph id's,
216 unsigned int Paragraph::Private::paragraph_id = 0;
217
218 namespace {
219
220 struct special_phrase {
221         string phrase;
222         docstring macro;
223         bool builtin;
224 };
225
226 special_phrase const special_phrases[] = {
227         { "LyX", from_ascii("\\LyX{}"), false },
228         { "TeX", from_ascii("\\TeX{}"), true },
229         { "LaTeX2e", from_ascii("\\LaTeXe{}"), true },
230         { "LaTeX", from_ascii("\\LaTeX{}"), true },
231 };
232
233 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
234
235 } // namespace anon
236
237
238 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
239         : owner_(owner), inset_owner_(0), begin_of_body_(0), layout_(&layout)
240 {
241         id_ = paragraph_id++;
242         text_.reserve(100);
243 }
244
245
246 Paragraph::Private::Private(Private const & p, Paragraph * owner)
247         : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_), 
248           params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
249           begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
250           layout_(p.layout_)
251 {
252         id_ = paragraph_id++;
253 }
254
255
256 Paragraph::Private::Private(Private const & p, Paragraph * owner,
257         pos_type beg, pos_type end)
258         : owner_(owner), inset_owner_(p.inset_owner_),
259           params_(p.params_), changes_(p.changes_),
260           insetlist_(p.insetlist_, beg, end),
261           begin_of_body_(p.begin_of_body_), words_(p.words_),
262           layout_(p.layout_)
263 {
264         id_ = paragraph_id++;
265         if (beg >= pos_type(p.text_.size()))
266                 return;
267         text_ = p.text_.substr(beg, end - beg);
268
269         FontList::const_iterator fcit = fontlist_.begin();
270         FontList::const_iterator fend = fontlist_.end();
271         for (; fcit != fend; ++fcit) {
272                 if (fcit->pos() < beg)
273                         continue;
274                 if (fcit->pos() >= end) {
275                         // Add last entry in the fontlist_.
276                         fontlist_.set(text_.size() - 1, fcit->font());
277                         break;
278                 }
279                 // Add a new entry in the fontlist_.
280                 fontlist_.set(fcit->pos() - beg, fcit->font());
281         }
282 }
283
284
285 void Paragraph::addChangesToToc(DocIterator const & cdit,
286         Buffer const & buf) const
287 {
288         d->changes_.addToToc(cdit, buf);
289 }
290
291
292 bool Paragraph::isFullyDeleted(pos_type start, pos_type end) const
293 {
294         LASSERT(start >= 0 && start <= size(), /**/);
295         LASSERT(end > start && end <= size() + 1, /**/);
296
297         return d->changes_.isFullyDeleted(start, end);
298 }
299
300
301 bool Paragraph::isChanged(pos_type start, pos_type end) const
302 {
303         LASSERT(start >= 0 && start <= size(), /**/);
304         LASSERT(end > start && end <= size() + 1, /**/);
305
306         return d->changes_.isChanged(start, end);
307 }
308
309
310 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
311 {
312         // keep the logic here in sync with the logic of eraseChars()
313         if (!trackChanges)
314                 return true;
315
316         Change const change = d->changes_.lookup(size());
317         return change.type == Change::INSERTED && change.author == 0;
318 }
319
320
321 void Paragraph::setChange(Change const & change)
322 {
323         // beware of the imaginary end-of-par character!
324         d->changes_.set(change, 0, size() + 1);
325
326         /*
327          * Propagate the change recursively - but not in case of DELETED!
328          *
329          * Imagine that your co-author makes changes in an existing inset. He
330          * sends your document to you and you come to the conclusion that the
331          * inset should go completely. If you erase it, LyX must not delete all
332          * text within the inset. Otherwise, the change tracked insertions of
333          * your co-author get lost and there is no way to restore them later.
334          *
335          * Conclusion: An inset's content should remain untouched if you delete it
336          */
337
338         if (change.type != Change::DELETED) {
339                 for (pos_type pos = 0; pos < size(); ++pos) {
340                         if (Inset * inset = getInset(pos))
341                                 inset->setChange(change);
342                 }
343         }
344 }
345
346
347 void Paragraph::setChange(pos_type pos, Change const & change)
348 {
349         LASSERT(pos >= 0 && pos <= size(), /**/);
350         d->changes_.set(change, pos);
351
352         // see comment in setChange(Change const &) above
353         if (change.type != Change::DELETED && pos < size())
354                         if (Inset * inset = getInset(pos))
355                                 inset->setChange(change);
356 }
357
358
359 Change const & Paragraph::lookupChange(pos_type pos) const
360 {
361         LASSERT(pos >= 0 && pos <= size(), /**/);
362         return d->changes_.lookup(pos);
363 }
364
365
366 void Paragraph::acceptChanges(BufferParams const & bparams, pos_type start,
367                 pos_type end)
368 {
369         LASSERT(start >= 0 && start <= size(), /**/);
370         LASSERT(end > start && end <= size() + 1, /**/);
371
372         for (pos_type pos = start; pos < end; ++pos) {
373                 switch (lookupChange(pos).type) {
374                         case Change::UNCHANGED:
375                                 // accept changes in nested inset
376                                 if (Inset * inset = getInset(pos))
377                                         inset->acceptChanges(bparams);
378                                 break;
379
380                         case Change::INSERTED:
381                                 d->changes_.set(Change(Change::UNCHANGED), pos);
382                                 // also accept changes in nested inset
383                                 if (Inset * inset = getInset(pos))
384                                         inset->acceptChanges(bparams);
385                                 break;
386
387                         case Change::DELETED:
388                                 // Suppress access to non-existent
389                                 // "end-of-paragraph char"
390                                 if (pos < size()) {
391                                         eraseChar(pos, false);
392                                         --end;
393                                         --pos;
394                                 }
395                                 break;
396                 }
397
398         }
399 }
400
401
402 void Paragraph::rejectChanges(BufferParams const & bparams,
403                 pos_type start, pos_type end)
404 {
405         LASSERT(start >= 0 && start <= size(), /**/);
406         LASSERT(end > start && end <= size() + 1, /**/);
407
408         for (pos_type pos = start; pos < end; ++pos) {
409                 switch (lookupChange(pos).type) {
410                         case Change::UNCHANGED:
411                                 // reject changes in nested inset
412                                 if (Inset * inset = getInset(pos))
413                                                 inset->rejectChanges(bparams);
414                                 break;
415
416                         case Change::INSERTED:
417                                 // Suppress access to non-existent
418                                 // "end-of-paragraph char"
419                                 if (pos < size()) {
420                                         eraseChar(pos, false);
421                                         --end;
422                                         --pos;
423                                 }
424                                 break;
425
426                         case Change::DELETED:
427                                 d->changes_.set(Change(Change::UNCHANGED), pos);
428
429                                 // Do NOT reject changes within a deleted inset!
430                                 // There may be insertions of a co-author inside of it!
431
432                                 break;
433                 }
434         }
435 }
436
437
438 void Paragraph::Private::insertChar(pos_type pos, char_type c,
439                 Change const & change)
440 {
441         LASSERT(pos >= 0 && pos <= int(text_.size()), /**/);
442
443         // track change
444         changes_.insert(change, pos);
445
446         // This is actually very common when parsing buffers (and
447         // maybe inserting ascii text)
448         if (pos == pos_type(text_.size())) {
449                 // when appending characters, no need to update tables
450                 text_.push_back(c);
451                 return;
452         }
453
454         text_.insert(text_.begin() + pos, c);
455
456         // Update the font table.
457         fontlist_.increasePosAfterPos(pos);
458
459         // Update the insets
460         insetlist_.increasePosAfterPos(pos);
461 }
462
463
464 bool Paragraph::insertInset(pos_type pos, Inset * inset,
465                                    Change const & change)
466 {
467         LASSERT(inset, /**/);
468         LASSERT(pos >= 0 && pos <= size(), /**/);
469
470         // Paragraph::insertInset() can be used in cut/copy/paste operation where
471         // d->inset_owner_ is not set yet.
472         if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
473                 return false;
474
475         d->insertChar(pos, META_INSET, change);
476         LASSERT(d->text_[pos] == META_INSET, /**/);
477
478         // Add a new entry in the insetlist_.
479         d->insetlist_.insert(inset, pos);
480         return true;
481 }
482
483
484 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
485 {
486         LASSERT(pos >= 0 && pos <= size(), return false);
487
488         // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
489
490         if (trackChanges) {
491                 Change change = d->changes_.lookup(pos);
492
493                 // set the character to DELETED if
494                 //  a) it was previously unchanged or
495                 //  b) it was inserted by a co-author
496
497                 if (change.type == Change::UNCHANGED ||
498                     (change.type == Change::INSERTED && change.author != 0)) {
499                         setChange(pos, Change(Change::DELETED));
500                         return false;
501                 }
502
503                 if (change.type == Change::DELETED)
504                         return false;
505         }
506
507         // Don't physically access the imaginary end-of-paragraph character.
508         // eraseChar() can only mark it as DELETED. A physical deletion of
509         // end-of-par must be handled externally.
510         if (pos == size()) {
511                 return false;
512         }
513
514         // track change
515         d->changes_.erase(pos);
516
517         // if it is an inset, delete the inset entry
518         if (d->text_[pos] == META_INSET)
519                 d->insetlist_.erase(pos);
520
521         d->text_.erase(d->text_.begin() + pos);
522
523         // Update the fontlist_
524         d->fontlist_.erase(pos);
525
526         // Update the insetlist_
527         d->insetlist_.decreasePosAfterPos(pos);
528
529         return true;
530 }
531
532
533 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
534 {
535         LASSERT(start >= 0 && start <= size(), /**/);
536         LASSERT(end >= start && end <= size() + 1, /**/);
537
538         pos_type i = start;
539         for (pos_type count = end - start; count; --count) {
540                 if (!eraseChar(i, trackChanges))
541                         ++i;
542         }
543         return end - i;
544 }
545
546
547 int Paragraph::Private::latexSurrogatePair(odocstream & os, char_type c,
548                 char_type next, Encoding const & encoding)
549 {
550         // Writing next here may circumvent a possible font change between
551         // c and next. Since next is only output if it forms a surrogate pair
552         // with c we can ignore this:
553         // A font change inside a surrogate pair does not make sense and is
554         // hopefully impossible to input.
555         // FIXME: change tracking
556         // Is this correct WRT change tracking?
557         docstring const latex1 = encoding.latexChar(next);
558         docstring const latex2 = encoding.latexChar(c);
559         if (docstring(1, next) == latex1) {
560                 // the encoding supports the combination
561                 os << latex2 << latex1;
562                 return latex1.length() + latex2.length();
563         } else
564                 os << latex1 << '{' << latex2 << '}';
565         return latex1.length() + latex2.length() + 2;
566 }
567
568
569 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
570                                        odocstream & os, TexRow & texrow,
571                                        pos_type i,
572                                        unsigned int & column,
573                                        Font const & font,
574                                        Layout const & style)
575 {
576         if (style.pass_thru || runparams.verbatim)
577                 return false;
578
579         if (i + 1 < int(text_.size())) {
580                 char_type next = text_[i + 1];
581                 if (Encodings::isCombiningChar(next)) {
582                         Encoding const & encoding = *(runparams.encoding);
583                         // This space has an accent, so we must always output it.
584                         column += latexSurrogatePair(os, ' ', next, encoding) - 1;
585                         return true;
586                 }
587         }
588
589         if (lyxrc.plaintext_linelen > 0
590             && column > lyxrc.plaintext_linelen
591             && i
592             && text_[i - 1] != ' '
593             && (i + 1 < int(text_.size()))
594             // same in FreeSpacing mode
595             && !owner_->isFreeSpacing()
596             // In typewriter mode, we want to avoid
597             // ! . ? : at the end of a line
598             && !(font.fontInfo().family() == TYPEWRITER_FAMILY
599                  && (text_[i - 1] == '.'
600                      || text_[i - 1] == '?'
601                      || text_[i - 1] == ':'
602                      || text_[i - 1] == '!'))) {
603                 os << '\n';
604                 texrow.newline();
605                 texrow.start(owner_->id(), i + 1);
606                 column = 0;
607         } else if (style.free_spacing) {
608                 os << '~';
609         } else {
610                 os << ' ';
611         }
612         return false;
613 }
614
615
616 int Paragraph::Private::writeScriptChars(odocstream & os,
617                                          docstring const & ltx,
618                                          Change const & runningChange,
619                                          Encoding const & encoding,
620                                          pos_type & i)
621 {
622         // FIXME: modifying i here is not very nice...
623
624         // We only arrive here when a proper language for character text_[i] has
625         // not been specified (i.e., it could not be translated in the current
626         // latex encoding) or its latex translation has been forced, and it
627         // belongs to a known script.
628         // Parameter ltx contains the latex translation of text_[i] as specified
629         // in the unicodesymbols file and is something like "\textXXX{<spec>}".
630         // The latex macro name "textXXX" specifies the script to which text_[i]
631         // belongs and we use it in order to check whether characters from the
632         // same script immediately follow, such that we can collect them in a
633         // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
634         // for the first char but only "<spec>" for all subsequent chars.
635         docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
636         docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
637         string script = to_ascii(ltx.substr(1, brace1 - 1));
638         int pos = 0;
639         int length = brace2;
640         bool closing_brace = true;
641         if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
642                 // Correct encoding is being used, so we can avoid \textgreek.
643                 pos = brace1 + 1;
644                 length -= pos;
645                 closing_brace = false;
646         }
647         os << ltx.substr(pos, length);
648         int size = text_.size();
649         while (i + 1 < size) {
650                 char_type const next = text_[i + 1];
651                 // Stop here if next character belongs to another script
652                 // or there is a change in change tracking status.
653                 if (!Encodings::isKnownScriptChar(next, script) ||
654                     runningChange != owner_->lookupChange(i + 1))
655                         break;
656                 Font prev_font;
657                 bool found = false;
658                 FontList::const_iterator cit = fontlist_.begin();
659                 FontList::const_iterator end = fontlist_.end();
660                 for (; cit != end; ++cit) {
661                         if (cit->pos() >= i && !found) {
662                                 prev_font = cit->font();
663                                 found = true;
664                         }
665                         if (cit->pos() >= i + 1)
666                                 break;
667                 }
668                 // Stop here if there is a font attribute or encoding change.
669                 if (found && cit != end && prev_font != cit->font())
670                         break;
671                 docstring const latex = encoding.latexChar(next);
672                 docstring::size_type const b1 =
673                                         latex.find_first_of(from_ascii("{"));
674                 docstring::size_type const b2 =
675                                         latex.find_last_of(from_ascii("}"));
676                 int const len = b2 - b1 - 1;
677                 os << latex.substr(b1 + 1, len);
678                 length += len;
679                 ++i;
680         }
681         if (closing_brace) {
682                 os << '}';
683                 ++length;
684         }
685         return length;
686 }
687
688
689 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
690 {
691         pos_type const len = str.length();
692
693         // is the paragraph large enough?
694         if (pos + len > int(text_.size()))
695                 return false;
696
697         // does the wanted text start at point?
698         for (string::size_type i = 0; i < str.length(); ++i) {
699                 // Caution: direct comparison of characters works only
700                 // because str is pure ASCII.
701                 if (str[i] != text_[pos + i])
702                         return false;
703         }
704
705         return fontlist_.hasChangeInRange(pos, len);
706 }
707
708
709 void Paragraph::Private::latexInset(
710                                              BufferParams const & bparams,
711                                              odocstream & os,
712                                              TexRow & texrow,
713                                              OutputParams & runparams,
714                                              Font & running_font,
715                                              Font & basefont,
716                                              Font const & outerfont,
717                                              bool & open_font,
718                                              Change & running_change,
719                                              Layout const & style,
720                                              pos_type & i,
721                                              unsigned int & column)
722 {
723         Inset * inset = owner_->getInset(i);
724         LASSERT(inset, /**/);
725
726         if (style.pass_thru) {
727                 inset->plaintext(os, runparams);
728                 return;
729         }
730
731         // FIXME: move this to InsetNewline::latex
732         if (inset->lyxCode() == NEWLINE_CODE) {
733                 // newlines are handled differently here than
734                 // the default in simpleTeXSpecialChars().
735                 if (!style.newline_allowed) {
736                         os << '\n';
737                 } else {
738                         if (open_font) {
739                                 column += running_font.latexWriteEndChanges(
740                                         os, bparams, runparams,
741                                         basefont, basefont);
742                                 open_font = false;
743                         }
744
745                         if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
746                                 os << '~';
747
748                         basefont = owner_->getLayoutFont(bparams, outerfont);
749                         running_font = basefont;
750
751                         if (runparams.moving_arg)
752                                 os << "\\protect ";
753
754                 }
755                 texrow.newline();
756                 texrow.start(owner_->id(), i + 1);
757                 column = 0;
758         }
759
760         if (owner_->lookupChange(i).type == Change::DELETED) {
761                 if( ++runparams.inDeletedInset == 1)
762                         runparams.changeOfDeletedInset = owner_->lookupChange(i);
763         }
764
765         if (inset->canTrackChanges()) {
766                 column += Changes::latexMarkChange(os, bparams, running_change,
767                         Change(Change::UNCHANGED));
768                 running_change = Change(Change::UNCHANGED);
769         }
770
771         bool close = false;
772         odocstream::pos_type const len = os.tellp();
773
774         if (inset->forceLTR() 
775             && running_font.isRightToLeft()
776                 // ERT is an exception, it should be output with no decorations at all
777                 && inset->lyxCode() != ERT_CODE) {
778                 if (running_font.language()->lang() == "farsi")
779                         os << "\\beginL{}";
780                 else
781                         os << "\\L{";
782                 close = true;
783         }
784
785         // FIXME: Bug: we can have an empty font change here!
786         // if there has just been a font change, we are going to close it
787         // right now, which means stupid latex code like \textsf{}. AFAIK,
788         // this does not harm dvi output. A minor bug, thus (JMarc)
789
790         // Some insets cannot be inside a font change command.
791         // However, even such insets *can* be placed in \L or \R
792         // or their equivalents (for RTL language switches), so we don't
793         // close the language in those cases.
794         // ArabTeX, though, cannot handle this special behavior, it seems.
795         bool arabtex = basefont.language()->lang() == "arabic_arabtex"
796                 || running_font.language()->lang() == "arabic_arabtex";
797         if (open_font && inset->noFontChange()) {
798                 bool closeLanguage = arabtex
799                         || basefont.isRightToLeft() == running_font.isRightToLeft();
800                 unsigned int count = running_font.latexWriteEndChanges(os,
801                         bparams, runparams, basefont, basefont, closeLanguage);
802                 column += count;
803                 // if any font properties were closed, update the running_font, 
804                 // making sure, however, to leave the language as it was
805                 if (count > 0) {
806                         // FIXME: probably a better way to keep track of the old 
807                         // language, than copying the entire font?
808                         Font const copy_font(running_font);
809                         basefont = owner_->getLayoutFont(bparams, outerfont);
810                         running_font = basefont;
811                         if (!closeLanguage)
812                                 running_font.setLanguage(copy_font.language());
813                         // leave font open if language is still open
814                         open_font = (running_font.language() == basefont.language());
815                         if (closeLanguage)
816                                 runparams.local_font = &basefont;
817                 }
818         }
819
820         int tmp;
821
822         try {
823                 tmp = inset->latex(os, runparams);
824         } catch (EncodingException & e) {
825                 // add location information and throw again.
826                 e.par_id = id_;
827                 e.pos = i;
828                 throw(e);
829         }
830
831         if (close) {
832                 if (running_font.language()->lang() == "farsi")
833                                 os << "\\endL{}";
834                         else
835                                 os << '}';
836         }
837
838         if (tmp) {
839                 for (int j = 0; j < tmp; ++j)
840                         texrow.newline();
841
842                 texrow.start(owner_->id(), i + 1);
843                 column = 0;
844         } else {
845                 column += os.tellp() - len;
846         }
847
848         if (owner_->lookupChange(i).type == Change::DELETED)
849                 --runparams.inDeletedInset;
850 }
851
852
853 void Paragraph::Private::latexSpecialChar(
854                                              odocstream & os,
855                                              OutputParams const & runparams,
856                                              Font const & running_font,
857                                              Change const & running_change,
858                                              Layout const & style,
859                                              pos_type & i,
860                                              unsigned int & column)
861 {
862         char_type const c = text_[i];
863
864         if (style.pass_thru) {
865                 if (c != '\0')
866                         // FIXME UNICODE: This can fail if c cannot
867                         // be encoded in the current encoding.
868                         os.put(c);
869                 return;
870         }
871
872         if (runparams.verbatim) {
873                 // FIXME UNICODE: This can fail if c cannot
874                 // be encoded in the current encoding.
875                 os.put(c);
876                 return;
877         }
878
879         // If T1 font encoding is used, use the special
880         // characters it provides.
881         // NOTE: some languages reset the font encoding
882         // internally
883         if (!running_font.language()->internalFontEncoding()
884             && lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
885                 return;
886
887         // \tt font needs special treatment
888         if (running_font.fontInfo().family() == TYPEWRITER_FAMILY
889                 && latexSpecialTypewriter(c, os, i, column))
890                 return;
891
892         // Otherwise, we use what LaTeX provides us.
893         switch (c) {
894         case '\\':
895                 os << "\\textbackslash{}";
896                 column += 15;
897                 break;
898         case '<':
899                 os << "\\textless{}";
900                 column += 10;
901                 break;
902         case '>':
903                 os << "\\textgreater{}";
904                 column += 13;
905                 break;
906         case '|':
907                 os << "\\textbar{}";
908                 column += 9;
909                 break;
910         case '-':
911                 os << '-';
912                 break;
913         case '\"':
914                 os << "\\char`\\\"{}";
915                 column += 9;
916                 break;
917
918         case '$': case '&':
919         case '%': case '#': case '{':
920         case '}': case '_':
921                 os << '\\';
922                 os.put(c);
923                 column += 1;
924                 break;
925
926         case '~':
927                 os << "\\textasciitilde{}";
928                 column += 16;
929                 break;
930
931         case '^':
932                 os << "\\textasciicircum{}";
933                 column += 17;
934                 break;
935
936         case '*':
937         case '[':
938         case ']':
939                 // avoid being mistaken for optional arguments
940                 os << '{';
941                 os.put(c);
942                 os << '}';
943                 column += 2;
944                 break;
945
946         case ' ':
947                 // Blanks are printed before font switching.
948                 // Sure? I am not! (try nice-latex)
949                 // I am sure it's correct. LyX might be smarter
950                 // in the future, but for now, nothing wrong is
951                 // written. (Asger)
952                 break;
953
954         default:
955                 // LyX, LaTeX etc.
956                 if (latexSpecialPhrase(os, i, column, runparams))
957                         return;
958
959                 if (c == '\0')
960                         return;
961
962                 Encoding const & encoding = *(runparams.encoding);
963                 if (i + 1 < int(text_.size())) {
964                         char_type next = text_[i + 1];
965                         if (Encodings::isCombiningChar(next)) {
966                                 column += latexSurrogatePair(os, c, next, encoding) - 1;
967                                 ++i;
968                                 break;
969                         }
970                 }
971                 string script;
972                 docstring const latex = encoding.latexChar(c);
973                 if (Encodings::isKnownScriptChar(c, script)
974                     && prefixIs(latex, from_ascii("\\" + script)))
975                         column += writeScriptChars(os, latex,
976                                         running_change, encoding, i) - 1;
977                 else if (latex.length() > 1 && latex[latex.length() - 1] != '}') {
978                         // Prevent eating of a following
979                         // space or command corruption by
980                         // following characters
981                         column += latex.length() + 1;
982                         os << latex << "{}";
983                 } else {
984                         column += latex.length() - 1;
985                         os << latex;
986                 }
987                 break;
988         }
989 }
990
991
992 bool Paragraph::Private::latexSpecialT1(char_type const c, odocstream & os,
993         pos_type i, unsigned int & column)
994 {
995         switch (c) {
996         case '>':
997         case '<':
998                 os.put(c);
999                 // In T1 encoding, these characters exist
1000                 // but we should avoid ligatures
1001                 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1002                         return true;
1003                 os << "\\textcompwordmark{}";
1004                 column += 19;
1005                 return true;
1006         case '|':
1007                 os.put(c);
1008                 return true;
1009         case '\"':
1010                 // soul.sty breaks with \char`\"
1011                 os << "\\textquotedbl{}";
1012                 column += 14;
1013                 return true;
1014         default:
1015                 return false;
1016         }
1017 }
1018
1019
1020 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, odocstream & os,
1021         pos_type i, unsigned int & column)
1022 {
1023         switch (c) {
1024         case '-':
1025                 // within \ttfamily, "--" is merged to "-" (no endash)
1026                 // so we avoid this rather irritating ligature
1027                 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
1028                         os << "-{}";
1029                         column += 2;
1030                 } else
1031                         os << '-';
1032                 return true;
1033
1034         // everything else has to be checked separately
1035         // (depending on the encoding)
1036         default:
1037                 return false;
1038         }
1039 }
1040
1041
1042 bool Paragraph::Private::latexSpecialPhrase(odocstream & os, pos_type & i,
1043         unsigned int & column, OutputParams const & runparams)
1044 {
1045         // FIXME: if we have "LaTeX" with a font
1046         // change in the middle (before the 'T', then
1047         // the "TeX" part is still special cased.
1048         // Really we should only operate this on
1049         // "words" for some definition of word
1050
1051         for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1052                 if (!isTextAt(special_phrases[pnr].phrase, i))
1053                         continue;
1054                 if (runparams.moving_arg)
1055                         os << "\\protect";
1056                 os << special_phrases[pnr].macro;
1057                 i += special_phrases[pnr].phrase.length() - 1;
1058                 column += special_phrases[pnr].macro.length() - 1;
1059                 return true;
1060         }
1061         return false;
1062 }
1063
1064
1065 void Paragraph::Private::validate(LaTeXFeatures & features,
1066                                 Layout const & layout) const
1067 {
1068         // check the params.
1069         if (!params_.spacing().isDefault())
1070                 features.require("setspace");
1071
1072         // then the layouts
1073         features.useLayout(layout.name());
1074
1075         // then the fonts
1076         fontlist_.validate(features);
1077
1078         // then the indentation
1079         if (!params_.leftIndent().zero())
1080                 features.require("ParagraphLeftIndent");
1081
1082         // then the insets
1083         InsetList::const_iterator icit = insetlist_.begin();
1084         InsetList::const_iterator iend = insetlist_.end();
1085         for (; icit != iend; ++icit) {
1086                 if (icit->inset) {
1087                         icit->inset->validate(features);
1088                         if (layout.needprotect &&
1089                             icit->inset->lyxCode() == FOOT_CODE)
1090                                 features.require("NeedLyXFootnoteCode");
1091                 }
1092         }
1093
1094         // then the contents
1095         for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1096                 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1097                         if (!special_phrases[pnr].builtin
1098                             && isTextAt(special_phrases[pnr].phrase, i)) {
1099                                 features.require(special_phrases[pnr].phrase);
1100                                 break;
1101                         }
1102                 }
1103                 Encodings::validate(text_[i], features);
1104         }
1105 }
1106
1107 /////////////////////////////////////////////////////////////////////
1108 //
1109 // Paragraph
1110 //
1111 /////////////////////////////////////////////////////////////////////
1112
1113 namespace {
1114         Layout const emptyParagraphLayout;
1115 }
1116
1117 Paragraph::Paragraph() 
1118         : d(new Paragraph::Private(this, emptyParagraphLayout))
1119 {
1120         itemdepth = 0;
1121         d->params_.clear();
1122 }
1123
1124
1125 Paragraph::Paragraph(Paragraph const & par)
1126         : itemdepth(par.itemdepth),
1127         d(new Paragraph::Private(*par.d, this))
1128 {
1129         registerWords();
1130 }
1131
1132
1133 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1134         : itemdepth(par.itemdepth),
1135         d(new Paragraph::Private(*par.d, this, beg, end))
1136 {
1137         registerWords();
1138 }
1139
1140
1141 Paragraph & Paragraph::operator=(Paragraph const & par)
1142 {
1143         // needed as we will destroy the private part before copying it
1144         if (&par != this) {
1145                 itemdepth = par.itemdepth;
1146
1147                 deregisterWords();
1148                 delete d;
1149                 d = new Private(*par.d, this);
1150                 registerWords();
1151         }
1152         return *this;
1153 }
1154
1155
1156 Paragraph::~Paragraph()
1157 {
1158         deregisterWords();
1159         delete d;
1160 }
1161
1162
1163 void Paragraph::write(ostream & os, BufferParams const & bparams,
1164         depth_type & dth) const
1165 {
1166         // The beginning or end of a deeper (i.e. nested) area?
1167         if (dth != d->params_.depth()) {
1168                 if (d->params_.depth() > dth) {
1169                         while (d->params_.depth() > dth) {
1170                                 os << "\n\\begin_deeper";
1171                                 ++dth;
1172                         }
1173                 } else {
1174                         while (d->params_.depth() < dth) {
1175                                 os << "\n\\end_deeper";
1176                                 --dth;
1177                         }
1178                 }
1179         }
1180
1181         // First write the layout
1182         os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1183
1184         d->params_.write(os);
1185
1186         Font font1(inherit_font, bparams.language);
1187
1188         Change running_change = Change(Change::UNCHANGED);
1189
1190         int column = 0;
1191         for (pos_type i = 0; i <= size(); ++i) {
1192
1193                 Change const change = lookupChange(i);
1194                 Changes::lyxMarkChange(os, column, running_change, change);
1195                 running_change = change;
1196
1197                 if (i == size())
1198                         break;
1199
1200                 // Write font changes (ignore spelling markers)
1201                 Font font2 = getFontSettings(bparams, i);
1202                 font2.setMisspelled(false);
1203                 if (font2 != font1) {
1204                         font2.lyxWriteChanges(font1, os);
1205                         column = 0;
1206                         font1 = font2;
1207                 }
1208
1209                 char_type const c = d->text_[i];
1210                 switch (c) {
1211                 case META_INSET:
1212                         if (Inset const * inset = getInset(i)) {
1213                                 if (inset->directWrite()) {
1214                                         // international char, let it write
1215                                         // code directly so it's shorter in
1216                                         // the file
1217                                         inset->write(os);
1218                                 } else {
1219                                         if (i)
1220                                                 os << '\n';
1221                                         os << "\\begin_inset ";
1222                                         inset->write(os);
1223                                         os << "\n\\end_inset\n\n";
1224                                         column = 0;
1225                                 }
1226                         }
1227                         break;
1228                 case '\\':
1229                         os << "\n\\backslash\n";
1230                         column = 0;
1231                         break;
1232                 case '.':
1233                         if (i + 1 < size() && d->text_[i + 1] == ' ') {
1234                                 os << ".\n";
1235                                 column = 0;
1236                         } else
1237                                 os << '.';
1238                         break;
1239                 default:
1240                         if ((column > 70 && c == ' ')
1241                             || column > 79) {
1242                                 os << '\n';
1243                                 column = 0;
1244                         }
1245                         // this check is to amend a bug. LyX sometimes
1246                         // inserts '\0' this could cause problems.
1247                         if (c != '\0')
1248                                 os << to_utf8(docstring(1, c));
1249                         else
1250                                 LYXERR0("NUL char in structure.");
1251                         ++column;
1252                         break;
1253                 }
1254         }
1255
1256         os << "\n\\end_layout\n";
1257 }
1258
1259
1260 void Paragraph::validate(LaTeXFeatures & features) const
1261 {
1262         d->validate(features, *d->layout_);
1263 }
1264
1265
1266 void Paragraph::insert(pos_type start, docstring const & str,
1267                        Font const & font, Change const & change)
1268 {
1269         for (size_t i = 0, n = str.size(); i != n ; ++i)
1270                 insertChar(start + i, str[i], font, change);
1271 }
1272
1273
1274 void Paragraph::appendChar(char_type c, Font const & font,
1275                 Change const & change)
1276 {
1277         // track change
1278         d->changes_.insert(change, d->text_.size());
1279         // when appending characters, no need to update tables
1280         d->text_.push_back(c);
1281         setFont(d->text_.size() - 1, font);
1282 }
1283
1284
1285 void Paragraph::appendString(docstring const & s, Font const & font,
1286                 Change const & change)
1287 {
1288         pos_type end = s.size();
1289         size_t oldsize = d->text_.size();
1290         size_t newsize = oldsize + end;
1291         size_t capacity = d->text_.capacity();
1292         if (newsize >= capacity)
1293                 d->text_.reserve(max(capacity + 100, newsize));
1294
1295         // when appending characters, no need to update tables
1296         d->text_.append(s);
1297
1298         // FIXME: Optimize this!
1299         for (size_t i = oldsize; i != newsize; ++i) {
1300                 // track change
1301                 d->changes_.insert(change, i);
1302         }
1303         d->fontlist_.set(oldsize, font);
1304         d->fontlist_.set(newsize - 1, font);
1305 }
1306
1307
1308 void Paragraph::insertChar(pos_type pos, char_type c,
1309                            bool trackChanges)
1310 {
1311         d->insertChar(pos, c, Change(trackChanges ?
1312                            Change::INSERTED : Change::UNCHANGED));
1313 }
1314
1315
1316 void Paragraph::insertChar(pos_type pos, char_type c,
1317                            Font const & font, bool trackChanges)
1318 {
1319         d->insertChar(pos, c, Change(trackChanges ?
1320                            Change::INSERTED : Change::UNCHANGED));
1321         setFont(pos, font);
1322 }
1323
1324
1325 void Paragraph::insertChar(pos_type pos, char_type c,
1326                            Font const & font, Change const & change)
1327 {
1328         d->insertChar(pos, c, change);
1329         setFont(pos, font);
1330 }
1331
1332
1333 bool Paragraph::insertInset(pos_type pos, Inset * inset,
1334                             Font const & font, Change const & change)
1335 {
1336         bool const success = insertInset(pos, inset, change);
1337         // Set the font/language of the inset...
1338         setFont(pos, font);
1339         return success;
1340 }
1341
1342
1343 void Paragraph::resetFonts(Font const & font)
1344 {
1345         d->fontlist_.clear();
1346         d->fontlist_.set(0, font);
1347         d->fontlist_.set(d->text_.size() - 1, font);
1348 }
1349
1350 // Gets uninstantiated font setting at position.
1351 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1352                                          pos_type pos) const
1353 {
1354         if (pos > size()) {
1355                 LYXERR0("pos: " << pos << " size: " << size());
1356                 LASSERT(pos <= size(), /**/);
1357         }
1358
1359         FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1360         if (cit != d->fontlist_.end())
1361                 return cit->font();
1362
1363         if (pos == size() && !empty())
1364                 return getFontSettings(bparams, pos - 1);
1365
1366         // Optimisation: avoid a full font instantiation if there is no
1367         // language change from previous call.
1368         static Font previous_font;
1369         static Language const * previous_lang = 0;
1370         Language const * lang = getParLanguage(bparams);
1371         if (lang != previous_lang) {
1372                 previous_lang = lang;
1373                 previous_font = Font(inherit_font, lang);
1374         }
1375         return previous_font;
1376 }
1377
1378
1379 FontSpan Paragraph::fontSpan(pos_type pos) const
1380 {
1381         LASSERT(pos <= size(), /**/);
1382         pos_type start = 0;
1383
1384         FontList::const_iterator cit = d->fontlist_.begin();
1385         FontList::const_iterator end = d->fontlist_.end();
1386         for (; cit != end; ++cit) {
1387                 if (cit->pos() >= pos) {
1388                         if (pos >= beginOfBody())
1389                                 return FontSpan(max(start, beginOfBody()),
1390                                                 cit->pos());
1391                         else
1392                                 return FontSpan(start,
1393                                                 min(beginOfBody() - 1,
1394                                                          cit->pos()));
1395                 }
1396                 start = cit->pos() + 1;
1397         }
1398
1399         // This should not happen, but if so, we take no chances.
1400         // LYXERR0("Paragraph::getEndPosOfFontSpan: This should not happen!");
1401         return FontSpan(pos, pos);
1402 }
1403
1404
1405 // Gets uninstantiated font setting at position 0
1406 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1407 {
1408         if (!empty() && !d->fontlist_.empty())
1409                 return d->fontlist_.begin()->font();
1410
1411         // Optimisation: avoid a full font instantiation if there is no
1412         // language change from previous call.
1413         static Font previous_font;
1414         static Language const * previous_lang = 0;
1415         if (bparams.language != previous_lang) {
1416                 previous_lang = bparams.language;
1417                 previous_font = Font(inherit_font, bparams.language);
1418         }
1419
1420         return previous_font;
1421 }
1422
1423
1424 // Gets the fully instantiated font at a given position in a paragraph
1425 // This is basically the same function as Text::GetFont() in text2.cpp.
1426 // The difference is that this one is used for generating the LaTeX file,
1427 // and thus cosmetic "improvements" are disallowed: This has to deliver
1428 // the true picture of the buffer. (Asger)
1429 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1430                                  Font const & outerfont) const
1431 {
1432         LASSERT(pos >= 0, /**/);
1433
1434         Font font = getFontSettings(bparams, pos);
1435
1436         pos_type const body_pos = beginOfBody();
1437         FontInfo & fi = font.fontInfo();
1438         if (pos < body_pos)
1439                 fi.realize(d->layout_->labelfont);
1440         else
1441                 fi.realize(d->layout_->font);
1442
1443         fi.realize(outerfont.fontInfo());
1444         fi.realize(bparams.getFont().fontInfo());
1445
1446         return font;
1447 }
1448
1449
1450 Font const Paragraph::getLabelFont
1451         (BufferParams const & bparams, Font const & outerfont) const
1452 {
1453         FontInfo tmpfont = d->layout_->labelfont;
1454         tmpfont.realize(outerfont.fontInfo());
1455         tmpfont.realize(bparams.getFont().fontInfo());
1456         return Font(tmpfont, getParLanguage(bparams));
1457 }
1458
1459
1460 Font const Paragraph::getLayoutFont
1461         (BufferParams const & bparams, Font const & outerfont) const
1462 {
1463         FontInfo tmpfont = d->layout_->font;
1464         tmpfont.realize(outerfont.fontInfo());
1465         tmpfont.realize(bparams.getFont().fontInfo());
1466         return Font(tmpfont, getParLanguage(bparams));
1467 }
1468
1469
1470 /// Returns the height of the highest font in range
1471 FontSize Paragraph::highestFontInRange
1472         (pos_type startpos, pos_type endpos, FontSize def_size) const
1473 {
1474         return d->fontlist_.highestInRange(startpos, endpos, def_size);
1475 }
1476
1477
1478 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1479 {
1480         char_type c = d->text_[pos];
1481         if (!lyxrc.rtl_support)
1482                 return c;
1483
1484         char_type uc = c;
1485         switch (c) {
1486         case '(':
1487                 uc = ')';
1488                 break;
1489         case ')':
1490                 uc = '(';
1491                 break;
1492         case '[':
1493                 uc = ']';
1494                 break;
1495         case ']':
1496                 uc = '[';
1497                 break;
1498         case '{':
1499                 uc = '}';
1500                 break;
1501         case '}':
1502                 uc = '{';
1503                 break;
1504         case '<':
1505                 uc = '>';
1506                 break;
1507         case '>':
1508                 uc = '<';
1509                 break;
1510         }
1511         if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1512                 return uc;
1513         return c;
1514 }
1515
1516
1517 void Paragraph::setFont(pos_type pos, Font const & font)
1518 {
1519         LASSERT(pos <= size(), /**/);
1520
1521         // First, reduce font against layout/label font
1522         // Update: The setCharFont() routine in text2.cpp already
1523         // reduces font, so we don't need to do that here. (Asger)
1524         
1525         d->fontlist_.set(pos, font);
1526 }
1527
1528
1529 void Paragraph::makeSameLayout(Paragraph const & par)
1530 {
1531         d->layout_ = par.d->layout_;
1532         d->params_ = par.d->params_;
1533 }
1534
1535
1536 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1537 {
1538         if (isFreeSpacing())
1539                 return false;
1540
1541         int pos = 0;
1542         int count = 0;
1543
1544         while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1545                 if (eraseChar(pos, trackChanges))
1546                         ++count;
1547                 else
1548                         ++pos;
1549         }
1550
1551         return count > 0 || pos > 0;
1552 }
1553
1554
1555 bool Paragraph::hasSameLayout(Paragraph const & par) const
1556 {
1557         return par.d->layout_ == d->layout_
1558                 && d->params_.sameLayout(par.d->params_);
1559 }
1560
1561
1562 depth_type Paragraph::getDepth() const
1563 {
1564         return d->params_.depth();
1565 }
1566
1567
1568 depth_type Paragraph::getMaxDepthAfter() const
1569 {
1570         if (d->layout_->isEnvironment())
1571                 return d->params_.depth() + 1;
1572         else
1573                 return d->params_.depth();
1574 }
1575
1576
1577 char Paragraph::getAlign() const
1578 {
1579         if (d->params_.align() == LYX_ALIGN_LAYOUT)
1580                 return d->layout_->align;
1581         else
1582                 return d->params_.align();
1583 }
1584
1585
1586 docstring const & Paragraph::labelString() const
1587 {
1588         return d->params_.labelString();
1589 }
1590
1591
1592 // the next two functions are for the manual labels
1593 docstring const Paragraph::getLabelWidthString() const
1594 {
1595         if (d->layout_->margintype == MARGIN_MANUAL
1596             || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
1597                 return d->params_.labelWidthString();
1598         else
1599                 return _("Senseless with this layout!");
1600 }
1601
1602
1603 void Paragraph::setLabelWidthString(docstring const & s)
1604 {
1605         d->params_.labelWidthString(s);
1606 }
1607
1608
1609 docstring const Paragraph::translateIfPossible(docstring const & s,
1610                 BufferParams const & bparams) const
1611 {
1612         if (!isAscii(s) || s.empty()) {
1613                 // This must be a user defined layout. We cannot translate
1614                 // this, since gettext accepts only ascii keys.
1615                 return s;
1616         }
1617         // Probably standard layout, try to translate
1618         Messages & m = getMessages(getParLanguage(bparams)->code());
1619         return m.get(to_ascii(s));
1620 }
1621
1622
1623 docstring Paragraph::expandLabel(Layout const & layout,
1624                 BufferParams const & bparams, bool process_appendix) const
1625 {
1626         DocumentClass const & tclass = bparams.documentClass();
1627
1628         docstring fmt;
1629         if (process_appendix && d->params_.appendix())
1630                 fmt = translateIfPossible(layout.labelstring_appendix(),
1631                         bparams);
1632         else
1633                 fmt = translateIfPossible(layout.labelstring(), bparams);
1634
1635         if (fmt.empty() && layout.labeltype == LABEL_COUNTER 
1636             && !layout.counter.empty())
1637                 return tclass.counters().theCounter(layout.counter);
1638
1639         // handle 'inherited level parts' in 'fmt',
1640         // i.e. the stuff between '@' in   '@Section@.\arabic{subsection}'
1641         size_t const i = fmt.find('@', 0);
1642         if (i != docstring::npos) {
1643                 size_t const j = fmt.find('@', i + 1);
1644                 if (j != docstring::npos) {
1645                         docstring parent(fmt, i + 1, j - i - 1);
1646                         docstring label = from_ascii("??");
1647                         if (tclass.hasLayout(parent))
1648                                 docstring label = expandLabel(tclass[parent], bparams,
1649                                                       process_appendix);
1650                         fmt = docstring(fmt, 0, i) + label 
1651                                 + docstring(fmt, j + 1, docstring::npos);
1652                 }
1653         }
1654
1655         return tclass.counters().counterLabel(fmt);
1656 }
1657
1658
1659 void Paragraph::applyLayout(Layout const & new_layout)
1660 {
1661         d->layout_ = &new_layout;
1662         LyXAlignment const oldAlign = d->params_.align();
1663         
1664         if (!(oldAlign & d->layout_->alignpossible)) {
1665                 frontend::Alert::warning(_("Alignment not permitted"), 
1666                         _("The new layout does not permit the alignment previously used.\nSetting to default."));
1667                 d->params_.align(LYX_ALIGN_LAYOUT);
1668         }
1669 }
1670
1671
1672 pos_type Paragraph::beginOfBody() const
1673 {
1674         return d->begin_of_body_;
1675 }
1676
1677
1678 void Paragraph::setBeginOfBody()
1679 {
1680         if (d->layout_->labeltype != LABEL_MANUAL) {
1681                 d->begin_of_body_ = 0;
1682                 return;
1683         }
1684
1685         // Unroll the first two cycles of the loop
1686         // and remember the previous character to
1687         // remove unnecessary getChar() calls
1688         pos_type i = 0;
1689         pos_type end = size();
1690         if (i < end && !isNewline(i)) {
1691                 ++i;
1692                 char_type previous_char = 0;
1693                 char_type temp = 0;
1694                 if (i < end) {
1695                         previous_char = d->text_[i];
1696                         if (!isNewline(i)) {
1697                                 ++i;
1698                                 while (i < end && previous_char != ' ') {
1699                                         temp = d->text_[i];
1700                                         if (isNewline(i))
1701                                                 break;
1702                                         ++i;
1703                                         previous_char = temp;
1704                                 }
1705                         }
1706                 }
1707         }
1708
1709         d->begin_of_body_ = i;
1710 }
1711
1712
1713 bool Paragraph::forcePlainLayout() const
1714 {
1715         return inInset().forcePlainLayout();
1716 }
1717
1718
1719 bool Paragraph::allowParagraphCustomization() const
1720 {
1721         return inInset().allowParagraphCustomization();
1722 }
1723
1724
1725 bool Paragraph::usePlainLayout() const
1726 {
1727         return inInset().usePlainLayout();
1728 }
1729
1730
1731 namespace {
1732
1733 // paragraphs inside floats need different alignment tags to avoid
1734 // unwanted space
1735
1736 bool noTrivlistCentering(InsetCode code)
1737 {
1738         return code == FLOAT_CODE
1739                || code == WRAP_CODE
1740                || code == CELL_CODE;
1741 }
1742
1743
1744 string correction(string const & orig)
1745 {
1746         if (orig == "flushleft")
1747                 return "raggedright";
1748         if (orig == "flushright")
1749                 return "raggedleft";
1750         if (orig == "center")
1751                 return "centering";
1752         return orig;
1753 }
1754
1755
1756 string const corrected_env(string const & suffix, string const & env,
1757         InsetCode code, bool const lastpar)
1758 {
1759         string output = suffix + "{";
1760         if (noTrivlistCentering(code)) {
1761                 if (lastpar) {
1762                         // the last paragraph in non-trivlist-aligned
1763                         // context is special (to avoid unwanted whitespace)
1764                         if (suffix == "\\begin")
1765                                 return "\\" + correction(env) + "{}";
1766                         return string();
1767                 }
1768                 output += correction(env);
1769         } else
1770                 output += env;
1771         output += "}";
1772         if (suffix == "\\begin")
1773                 output += "\n";
1774         return output;
1775 }
1776
1777
1778 void adjust_row_column(string const & str, TexRow & texrow, int & column)
1779 {
1780         if (!contains(str, "\n"))
1781                 column += str.size();
1782         else {
1783                 string tmp;
1784                 texrow.newline();
1785                 column = rsplit(str, tmp, '\n').size();
1786         }
1787 }
1788
1789 } // namespace anon
1790
1791
1792 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
1793                                  odocstream & os, TexRow & texrow,
1794                                  OutputParams const & runparams) const
1795 {
1796         int column = 0;
1797
1798         if (params_.noindent()) {
1799                 os << "\\noindent ";
1800                 column += 10;
1801         }
1802         
1803         LyXAlignment const curAlign = params_.align();
1804
1805         if (curAlign == layout_->align)
1806                 return column;
1807
1808         switch (curAlign) {
1809         case LYX_ALIGN_NONE:
1810         case LYX_ALIGN_BLOCK:
1811         case LYX_ALIGN_LAYOUT:
1812         case LYX_ALIGN_SPECIAL:
1813                 break;
1814         case LYX_ALIGN_LEFT:
1815         case LYX_ALIGN_RIGHT:
1816         case LYX_ALIGN_CENTER:
1817                 if (runparams.moving_arg) {
1818                         os << "\\protect";
1819                         column += 8;
1820                 }
1821                 break;
1822         }
1823
1824         string const begin_tag = "\\begin";
1825         InsetCode code = owner_->ownerCode();
1826         bool const lastpar = runparams.isLastPar;
1827
1828         switch (curAlign) {
1829         case LYX_ALIGN_NONE:
1830         case LYX_ALIGN_BLOCK:
1831         case LYX_ALIGN_LAYOUT:
1832         case LYX_ALIGN_SPECIAL:
1833                 break;
1834         case LYX_ALIGN_LEFT: {
1835                 string output;
1836                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1837                         output = corrected_env(begin_tag, "flushleft", code, lastpar);
1838                 else
1839                         output = corrected_env(begin_tag, "flushright", code, lastpar);
1840                 os << from_ascii(output);
1841                 adjust_row_column(output, texrow, column);
1842                 break;
1843         } case LYX_ALIGN_RIGHT: {
1844                 string output;
1845                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1846                         output = corrected_env(begin_tag, "flushright", code, lastpar);
1847                 else
1848                         output = corrected_env(begin_tag, "flushleft", code, lastpar);
1849                 os << from_ascii(output);
1850                 adjust_row_column(output, texrow, column);
1851                 break;
1852         } case LYX_ALIGN_CENTER: {
1853                 string output;
1854                 output = corrected_env(begin_tag, "center", code, lastpar);
1855                 os << from_ascii(output);
1856                 adjust_row_column(output, texrow, column);
1857                 break;
1858         }
1859         }
1860
1861         return column;
1862 }
1863
1864
1865 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
1866                                odocstream & os, TexRow & texrow,
1867                                OutputParams const & runparams) const
1868 {
1869         int column = 0;
1870
1871         LyXAlignment const curAlign = params_.align();
1872
1873         if (curAlign == layout_->align)
1874                 return column;
1875
1876         switch (curAlign) {
1877         case LYX_ALIGN_NONE:
1878         case LYX_ALIGN_BLOCK:
1879         case LYX_ALIGN_LAYOUT:
1880         case LYX_ALIGN_SPECIAL:
1881                 break;
1882         case LYX_ALIGN_LEFT:
1883         case LYX_ALIGN_RIGHT:
1884         case LYX_ALIGN_CENTER:
1885                 if (runparams.moving_arg) {
1886                         os << "\\protect";
1887                         column = 8;
1888                 }
1889                 break;
1890         }
1891
1892         string const end_tag = "\n\\par\\end";
1893         InsetCode code = owner_->ownerCode();
1894         bool const lastpar = runparams.isLastPar;
1895
1896         switch (curAlign) {
1897         case LYX_ALIGN_NONE:
1898         case LYX_ALIGN_BLOCK:
1899         case LYX_ALIGN_LAYOUT:
1900         case LYX_ALIGN_SPECIAL:
1901                 break;
1902         case LYX_ALIGN_LEFT: {
1903                 string output;
1904                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1905                         output = corrected_env(end_tag, "flushleft", code, lastpar);
1906                 else
1907                         output = corrected_env(end_tag, "flushright", code, lastpar);
1908                 os << from_ascii(output);
1909                 adjust_row_column(output, texrow, column);
1910                 break;
1911         } case LYX_ALIGN_RIGHT: {
1912                 string output;
1913                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1914                         output = corrected_env(end_tag, "flushright", code, lastpar);
1915                 else
1916                         output = corrected_env(end_tag, "flushleft", code, lastpar);
1917                 os << from_ascii(output);
1918                 adjust_row_column(output, texrow, column);
1919                 break;
1920         } case LYX_ALIGN_CENTER: {
1921                 string output;
1922                 output = corrected_env(end_tag, "center", code, lastpar);
1923                 os << from_ascii(output);
1924                 adjust_row_column(output, texrow, column);
1925                 break;
1926         }
1927         }
1928
1929         return column;
1930 }
1931
1932
1933 // This one spits out the text of the paragraph
1934 bool Paragraph::latex(BufferParams const & bparams,
1935         Font const & outerfont,
1936         odocstream & os, TexRow & texrow,
1937         OutputParams const & runparams,
1938         int start_pos, int end_pos) const
1939 {
1940         LYXERR(Debug::LATEX, "Paragraph::latex...     " << this);
1941
1942         bool return_value = false;
1943
1944         bool const allowcust = allowParagraphCustomization();
1945
1946         // FIXME This check should not be needed. Perhaps issue an
1947         // error if it triggers.
1948         Layout const & style = forcePlainLayout() ?
1949                 bparams.documentClass().plainLayout() : *d->layout_;
1950
1951         // Current base font for all inherited font changes, without any
1952         // change caused by an individual character, except for the language:
1953         // It is set to the language of the first character.
1954         // As long as we are in the label, this font is the base font of the
1955         // label. Before the first body character it is set to the base font
1956         // of the body.
1957         Font basefont;
1958
1959         // Maybe we have to create a optional argument.
1960         pos_type body_pos = beginOfBody();
1961         unsigned int column = 0;
1962
1963         if (body_pos > 0) {
1964                 os << '[';
1965                 column += 1;
1966                 basefont = getLabelFont(bparams, outerfont);
1967         } else {
1968                 basefont = getLayoutFont(bparams, outerfont);
1969         }
1970
1971         // Which font is currently active?
1972         Font running_font(basefont);
1973         // Do we have an open font change?
1974         bool open_font = false;
1975
1976         Change runningChange = Change(Change::UNCHANGED);
1977
1978         texrow.start(id(), 0);
1979
1980         // if the paragraph is empty, the loop will not be entered at all
1981         if (empty()) {
1982                 if (style.isCommand()) {
1983                         os << '{';
1984                         ++column;
1985                 }
1986                 if (allowcust)
1987                         column += d->startTeXParParams(bparams, os, texrow,
1988                                                     runparams);
1989         }
1990
1991         for (pos_type i = 0; i < size(); ++i) {
1992                 // First char in paragraph or after label?
1993                 if (i == body_pos) {
1994                         if (body_pos > 0) {
1995                                 if (open_font) {
1996                                         column += running_font.latexWriteEndChanges(
1997                                                 os, bparams, runparams,
1998                                                 basefont, basefont);
1999                                         open_font = false;
2000                                 }
2001                                 basefont = getLayoutFont(bparams, outerfont);
2002                                 running_font = basefont;
2003
2004                                 column += Changes::latexMarkChange(os, bparams,
2005                                                 runningChange, Change(Change::UNCHANGED));
2006                                 runningChange = Change(Change::UNCHANGED);
2007
2008                                 os << "] ";
2009                                 column +=2;
2010                         }
2011                         if (style.isCommand()) {
2012                                 os << '{';
2013                                 ++column;
2014                         }
2015
2016                         if (allowcust)
2017                                 column += d->startTeXParParams(bparams, os,
2018                                                             texrow,
2019                                                             runparams);
2020                 }
2021
2022                 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
2023                                                                  : lookupChange(i);
2024
2025                 if (bparams.outputChanges && runningChange != change) {
2026                         if (open_font) {
2027                                 column += running_font.latexWriteEndChanges(
2028                                                 os, bparams, runparams, basefont, basefont);
2029                                 open_font = false;
2030                         }
2031                         basefont = getLayoutFont(bparams, outerfont);
2032                         running_font = basefont;
2033
2034                         column += Changes::latexMarkChange(os, bparams, runningChange, change);
2035                         runningChange = change;
2036                 }
2037
2038                 // do not output text which is marked deleted
2039                 // if change tracking output is disabled
2040                 if (!bparams.outputChanges && change.type == Change::DELETED) {
2041                         continue;
2042                 }
2043
2044                 ++column;
2045
2046                 // Fully instantiated font
2047                 Font const font = getFont(bparams, i, outerfont);
2048
2049                 Font const last_font = running_font;
2050
2051                 // Do we need to close the previous font?
2052                 if (open_font &&
2053                     (font != running_font ||
2054                      font.language() != running_font.language()))
2055                 {
2056                         column += running_font.latexWriteEndChanges(
2057                                         os, bparams, runparams, basefont,
2058                                         (i == body_pos-1) ? basefont : font);
2059                         running_font = basefont;
2060                         open_font = false;
2061                 }
2062
2063                 // close babel's font environment before opening CJK.
2064                 if (!running_font.language()->babel().empty() &&
2065                     font.language()->encoding()->package() == Encoding::CJK) {
2066                                 string end_tag = subst(lyxrc.language_command_end,
2067                                                         "$$lang",
2068                                                         running_font.language()->babel());
2069                                 os << from_ascii(end_tag);
2070                                 column += end_tag.length();
2071                 }
2072
2073                 // Switch file encoding if necessary (and allowed)
2074                 if (!runparams.verbatim && 
2075                     runparams.encoding->package() != Encoding::none &&
2076                     font.language()->encoding()->package() != Encoding::none) {
2077                         pair<bool, int> const enc_switch = switchEncoding(os, bparams,
2078                                         runparams, *(font.language()->encoding()));
2079                         if (enc_switch.first) {
2080                                 column += enc_switch.second;
2081                                 runparams.encoding = font.language()->encoding();
2082                         }
2083                 }
2084
2085                 char_type const c = d->text_[i];
2086
2087                 // Do we need to change font?
2088                 if ((font != running_font ||
2089                      font.language() != running_font.language()) &&
2090                         i != body_pos - 1)
2091                 {
2092                         odocstringstream ods;
2093                         column += font.latexWriteStartChanges(ods, bparams,
2094                                                               runparams, basefont,
2095                                                               last_font);
2096                         running_font = font;
2097                         open_font = true;
2098                         docstring fontchange = ods.str();
2099                         // check if the fontchange ends with a trailing blank
2100                         // (like "\small " (see bug 3382)
2101                         if (suffixIs(fontchange, ' ') && c == ' ')
2102                                 os << fontchange.substr(0, fontchange.size() - 1) 
2103                                    << from_ascii("{}");
2104                         else
2105                                 os << fontchange;
2106                 }
2107
2108                 // FIXME: think about end_pos implementation...
2109                 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2110                         // FIXME: integrate this case in latexSpecialChar
2111                         // Do not print the separation of the optional argument
2112                         // if style.pass_thru is false. This works because
2113                         // latexSpecialChar ignores spaces if
2114                         // style.pass_thru is false.
2115                         if (i != body_pos - 1) {
2116                                 if (d->simpleTeXBlanks(
2117                                                 runparams, os, texrow,
2118                                                 i, column, font, style)) {
2119                                         // A surrogate pair was output. We
2120                                         // must not call latexSpecialChar
2121                                         // in this iteration, since it would output
2122                                         // the combining character again.
2123                                         ++i;
2124                                         continue;
2125                                 }
2126                         }
2127                 }
2128
2129                 OutputParams rp = runparams;
2130                 rp.free_spacing = style.free_spacing;
2131                 rp.local_font = &font;
2132                 rp.intitle = style.intitle;
2133
2134                 // Two major modes:  LaTeX or plain
2135                 // Handle here those cases common to both modes
2136                 // and then split to handle the two modes separately.
2137                 if (c == META_INSET) {
2138                         if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2139                                 d->latexInset(bparams, os,
2140                                                 texrow, rp, running_font,
2141                                                 basefont, outerfont, open_font,
2142                                                 runningChange, style, i, column);
2143                         }
2144                 } else {
2145                         if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2146                                 try {
2147                                         d->latexSpecialChar(os, rp, running_font, runningChange,
2148                                                 style, i, column);
2149                                 } catch (EncodingException & e) {
2150                                 if (runparams.dryrun) {
2151                                         os << "<" << _("LyX Warning: ")
2152                                            << _("uncodable character") << " '";
2153                                         os.put(c);
2154                                         os << "'>";
2155                                 } else {
2156                                         // add location information and throw again.
2157                                         e.par_id = id();
2158                                         e.pos = i;
2159                                         throw(e);
2160                                 }
2161                         }
2162                 }
2163                 }
2164
2165                 // Set the encoding to that returned from latexSpecialChar (see
2166                 // comment for encoding member in OutputParams.h)
2167                 runparams.encoding = rp.encoding;
2168         }
2169
2170         // If we have an open font definition, we have to close it
2171         if (open_font) {
2172 #ifdef FIXED_LANGUAGE_END_DETECTION
2173                 if (next_) {
2174                         running_font
2175                                 .latexWriteEndChanges(os, bparams, runparams,
2176                                         basefont,
2177                                         next_->getFont(bparams, 0, outerfont));
2178                 } else {
2179                         running_font.latexWriteEndChanges(os, bparams,
2180                                         runparams, basefont, basefont);
2181                 }
2182 #else
2183 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2184 //FIXME: there as we start another \selectlanguage with the next paragraph if
2185 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2186                 running_font.latexWriteEndChanges(os, bparams, runparams,
2187                                 basefont, basefont);
2188 #endif
2189         }
2190
2191         column += Changes::latexMarkChange(os, bparams, runningChange, Change(Change::UNCHANGED));
2192
2193         // Needed if there is an optional argument but no contents.
2194         if (body_pos > 0 && body_pos == size()) {
2195                 os << "]~";
2196                 return_value = false;
2197         }
2198
2199         if (allowcust) {
2200                 column += d->endTeXParParams(bparams, os, texrow,
2201                                           runparams);
2202         }
2203
2204         LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2205         return return_value;
2206 }
2207
2208
2209 bool Paragraph::emptyTag() const
2210 {
2211         for (pos_type i = 0; i < size(); ++i) {
2212                 if (Inset const * inset = getInset(i)) {
2213                         InsetCode lyx_code = inset->lyxCode();
2214                         if (lyx_code != TOC_CODE &&
2215                             lyx_code != INCLUDE_CODE &&
2216                             lyx_code != GRAPHICS_CODE &&
2217                             lyx_code != ERT_CODE &&
2218                             lyx_code != LISTINGS_CODE &&
2219                             lyx_code != FLOAT_CODE &&
2220                             lyx_code != TABULAR_CODE) {
2221                                 return false;
2222                         }
2223                 } else {
2224                         char_type c = d->text_[i];
2225                         if (c != ' ' && c != '\t')
2226                                 return false;
2227                 }
2228         }
2229         return true;
2230 }
2231
2232
2233 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2234         const
2235 {
2236         for (pos_type i = 0; i < size(); ++i) {
2237                 if (Inset const * inset = getInset(i)) {
2238                         InsetCode lyx_code = inset->lyxCode();
2239                         if (lyx_code == LABEL_CODE) {
2240                                 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2241                                 docstring const & id = il->getParam("name");
2242                                 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2243                         }
2244                 }
2245         }
2246         return string();
2247 }
2248
2249
2250 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2251         const
2252 {
2253         pos_type i;
2254         for (i = 0; i < size(); ++i) {
2255                 if (Inset const * inset = getInset(i)) {
2256                         inset->docbook(os, runparams);
2257                 } else {
2258                         char_type c = d->text_[i];
2259                         if (c == ' ')
2260                                 break;
2261                         os << sgml::escapeChar(c);
2262                 }
2263         }
2264         return i;
2265 }
2266
2267
2268 pos_type Paragraph::firstWordLyXHTML(odocstream & os, OutputParams const & runparams)
2269         const
2270 {
2271         pos_type i;
2272         for (i = 0; i < size(); ++i) {
2273                 if (Inset const * inset = getInset(i)) {
2274                         inset->xhtml(os, runparams);
2275                 } else {
2276                         char_type c = d->text_[i];
2277                         if (c == ' ')
2278                                 break;
2279                         os << html::escapeChar(c);
2280                 }
2281         }
2282         return i;
2283 }
2284
2285
2286 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2287 {
2288         Font font_old;
2289         pos_type size = text_.size();
2290         for (pos_type i = initial; i < size; ++i) {
2291                 Font font = owner_->getFont(buf.params(), i, outerfont);
2292                 if (text_[i] == META_INSET)
2293                         return false;
2294                 if (i != initial && font != font_old)
2295                         return false;
2296                 font_old = font;
2297         }
2298
2299         return true;
2300 }
2301
2302
2303 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2304                                     odocstream & os,
2305                                     OutputParams const & runparams,
2306                                     Font const & outerfont,
2307                                     pos_type initial) const
2308 {
2309         bool emph_flag = false;
2310
2311         Layout const & style = *d->layout_;
2312         FontInfo font_old =
2313                 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2314
2315         if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2316                 os << "]]>";
2317
2318         // parsing main loop
2319         for (pos_type i = initial; i < size(); ++i) {
2320                 Font font = getFont(buf.params(), i, outerfont);
2321
2322                 // handle <emphasis> tag
2323                 if (font_old.emph() != font.fontInfo().emph()) {
2324                         if (font.fontInfo().emph() == FONT_ON) {
2325                                 os << "<emphasis>";
2326                                 emph_flag = true;
2327                         } else if (i != initial) {
2328                                 os << "</emphasis>";
2329                                 emph_flag = false;
2330                         }
2331                 }
2332
2333                 if (Inset const * inset = getInset(i)) {
2334                         inset->docbook(os, runparams);
2335                 } else {
2336                         char_type c = d->text_[i];
2337
2338                         if (style.pass_thru)
2339                                 os.put(c);
2340                         else
2341                                 os << sgml::escapeChar(c);
2342                 }
2343                 font_old = font.fontInfo();
2344         }
2345
2346         if (emph_flag) {
2347                 os << "</emphasis>";
2348         }
2349
2350         if (style.free_spacing)
2351                 os << '\n';
2352         if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2353                 os << "<![CDATA[";
2354 }
2355
2356
2357 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
2358                                     odocstream & os,
2359                                     OutputParams const & runparams,
2360                                     Font const & outerfont,
2361                                     pos_type initial) const
2362 {
2363         docstring retval;
2364
2365         // FIXME We really need to manage the tag nesting here.
2366         // Probably in the same sort of way as in output_xhtml.
2367         bool emph_flag = false;
2368         bool bold_flag = false;
2369         std::string closing_tag;
2370
2371         Layout const & style = *d->layout_;
2372         FontInfo font_old =
2373                 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2374
2375         //if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2376         //      os << "]]>";
2377
2378         // parsing main loop
2379         for (pos_type i = initial; i < size(); ++i) {
2380                 Font font = getFont(buf.params(), i, outerfont);
2381
2382                 // emphasis
2383                 if (font_old.emph() != font.fontInfo().emph()) {
2384                         if (font.fontInfo().emph() == FONT_ON) {
2385                                 os << "<em>";
2386                                 emph_flag = true;
2387                         } else if (emph_flag && i != initial) {
2388                                 os << "</em>";
2389                                 emph_flag = false;
2390                         }
2391                 }
2392                 // bold
2393                 if (font_old.series() != font.fontInfo().series()) {
2394                         if (font.fontInfo().series() == BOLD_SERIES) {
2395                                 os << "<strong>";
2396                                 bold_flag = true;
2397                         } else if (bold_flag && i != initial) {
2398                                 os << "</strong>";
2399                                 bold_flag = false;
2400                         }
2401                 }
2402                 // FIXME Other such tags? 
2403
2404                 if (Inset const * inset = getInset(i)) {
2405                         retval += inset->xhtml(os, runparams);
2406                 } else {
2407                         char_type c = d->text_[i];
2408
2409                         if (style.pass_thru)
2410                                 os.put(c);
2411                         else if (c == '-') {
2412                                 docstring str;
2413                                 int j = i + 1;
2414                                 if (j < size() && d->text_[j] == '-') {
2415                                         j += 1;
2416                                         if (j < size() && d->text_[j] == '-') {
2417                                                 str += from_ascii("&mdash;");
2418                                                 i += 2;
2419                                         } else {
2420                                                 str += from_ascii("&ndash;");
2421                                                 i += 1;
2422                                         }
2423                                 }
2424                                 else
2425                                         str += c;
2426                                 os << str;
2427                         } else
2428                                 os << html::escapeChar(c);
2429                 }
2430                 font_old = font.fontInfo();
2431         }
2432
2433         // FIXME This could be out of order. See above.
2434         if (emph_flag)
2435                 os << "</em>";
2436         if (bold_flag)
2437                 os << "</strong>";
2438
2439         return retval;
2440 }
2441
2442
2443 bool Paragraph::isHfill(pos_type pos) const
2444 {
2445         Inset const * inset = getInset(pos);
2446         return inset && (inset->lyxCode() == SPACE_CODE &&
2447                          inset->isStretchableSpace());
2448 }
2449
2450
2451 bool Paragraph::isNewline(pos_type pos) const
2452 {
2453         Inset const * inset = getInset(pos);
2454         return inset && inset->lyxCode() == NEWLINE_CODE;
2455 }
2456
2457
2458 bool Paragraph::isLineSeparator(pos_type pos) const
2459 {
2460         char_type const c = d->text_[pos];
2461         if (isLineSeparatorChar(c))
2462                 return true;
2463         Inset const * inset = getInset(pos);
2464         return inset && inset->isLineSeparator();
2465 }
2466
2467
2468 bool Paragraph::isWordSeparator(pos_type pos) const
2469 {
2470         if (Inset const * inset = getInset(pos))
2471                 return !inset->isLetter();
2472         char_type const c = d->text_[pos];
2473         // We want to pass the ' and escape chars to the spellchecker
2474         static docstring const quote = from_utf8(lyxrc.spellchecker_esc_chars + '\'');
2475         return (!isLetterChar(c) && !isDigit(c) && !contains(quote, c))
2476                 || pos == size();
2477 }
2478
2479
2480 bool Paragraph::isChar(pos_type pos) const
2481 {
2482         if (Inset const * inset = getInset(pos))
2483                 return inset->isChar();
2484         char_type const c = d->text_[pos];
2485         return !isLetterChar(c) && !isDigit(c) && !lyx::isSpace(c);
2486 }
2487
2488
2489 bool Paragraph::isSpace(pos_type pos) const
2490 {
2491         if (Inset const * inset = getInset(pos))
2492                 return inset->isSpace();
2493         char_type const c = d->text_[pos];
2494         return lyx::isSpace(c);
2495 }
2496
2497
2498 Language const *
2499 Paragraph::getParLanguage(BufferParams const & bparams) const
2500 {
2501         if (!empty())
2502                 return getFirstFontSettings(bparams).language();
2503         // FIXME: we should check the prev par as well (Lgb)
2504         return bparams.language;
2505 }
2506
2507
2508 bool Paragraph::isRTL(BufferParams const & bparams) const
2509 {
2510         return lyxrc.rtl_support
2511                 && getParLanguage(bparams)->rightToLeft()
2512                 && ownerCode() != ERT_CODE
2513                 && ownerCode() != LISTINGS_CODE;
2514 }
2515
2516
2517 void Paragraph::changeLanguage(BufferParams const & bparams,
2518                                Language const * from, Language const * to)
2519 {
2520         // change language including dummy font change at the end
2521         for (pos_type i = 0; i <= size(); ++i) {
2522                 Font font = getFontSettings(bparams, i);
2523                 if (font.language() == from) {
2524                         font.setLanguage(to);
2525                         setFont(i, font);
2526                 }
2527         }
2528 }
2529
2530
2531 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2532 {
2533         Language const * doc_language = bparams.language;
2534         FontList::const_iterator cit = d->fontlist_.begin();
2535         FontList::const_iterator end = d->fontlist_.end();
2536
2537         for (; cit != end; ++cit)
2538                 if (cit->font().language() != ignore_language &&
2539                     cit->font().language() != latex_language &&
2540                     cit->font().language() != doc_language)
2541                         return true;
2542         return false;
2543 }
2544
2545
2546 docstring Paragraph::asString(int options) const
2547 {
2548         return asString(0, size(), options);
2549 }
2550
2551
2552 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
2553 {
2554         odocstringstream os;
2555
2556         if (beg == 0 
2557                 && options & AS_STR_LABEL
2558                 && !d->params_.labelString().empty())
2559                 os << d->params_.labelString() << ' ';
2560
2561         for (pos_type i = beg; i < end; ++i) {
2562                 char_type const c = d->text_[i];
2563                 if (isPrintable(c) || c == '\t'
2564                     || (c == '\n' && options & AS_STR_NEWLINES))
2565                         os.put(c);
2566                 else if (c == META_INSET && options & AS_STR_INSETS)
2567                         getInset(i)->tocString(os);
2568         }
2569
2570         return os.str();
2571 }
2572
2573
2574 docstring Paragraph::stringify(pos_type beg, pos_type end, int options, OutputParams & runparams) const
2575 {
2576         odocstringstream os;
2577
2578         if (beg == 0 
2579                 && options & AS_STR_LABEL
2580                 && !d->params_.labelString().empty())
2581                 os << d->params_.labelString() << ' ';
2582
2583         for (pos_type i = beg; i < end; ++i) {
2584                 char_type const c = d->text_[i];
2585                 if (isPrintable(c) || c == '\t'
2586                     || (c == '\n' && options & AS_STR_NEWLINES))
2587                         os.put(c);
2588                 else if (c == META_INSET && options & AS_STR_INSETS) {
2589                         getInset(i)->plaintext(os, runparams);
2590                 }
2591         }
2592
2593         return os.str();
2594 }
2595
2596
2597 void Paragraph::setInsetOwner(Inset const * inset)
2598 {
2599         d->inset_owner_ = inset;
2600 }
2601
2602
2603 int Paragraph::id() const
2604 {
2605         return d->id_;
2606 }
2607
2608
2609 Layout const & Paragraph::layout() const
2610 {
2611         return *d->layout_;
2612 }
2613
2614
2615 void Paragraph::setLayout(Layout const & layout)
2616 {
2617         d->layout_ = &layout;
2618 }
2619
2620
2621 void Paragraph::setDefaultLayout(DocumentClass const & tc)
2622
2623         setLayout(tc.defaultLayout()); 
2624 }
2625
2626
2627 void Paragraph::setPlainLayout(DocumentClass const & tc)
2628
2629         setLayout(tc.plainLayout()); 
2630 }
2631
2632
2633 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
2634 {
2635         if (usePlainLayout())
2636                 setPlainLayout(tclass);
2637         else
2638                 setDefaultLayout(tclass);
2639 }
2640
2641
2642 Inset const & Paragraph::inInset() const
2643 {
2644         LASSERT(d->inset_owner_, throw ExceptionMessage(BufferException,
2645                 _("Memory problem"), _("Paragraph not properly initialized")));
2646         return *d->inset_owner_;
2647 }
2648
2649
2650 InsetCode Paragraph::ownerCode() const
2651 {
2652         return d->inset_owner_ ? d->inset_owner_->lyxCode() : NO_CODE;
2653 }
2654
2655
2656 ParagraphParameters & Paragraph::params()
2657 {
2658         return d->params_;
2659 }
2660
2661
2662 ParagraphParameters const & Paragraph::params() const
2663 {
2664         return d->params_;
2665 }
2666
2667
2668 bool Paragraph::isFreeSpacing() const
2669 {
2670         if (d->layout_->free_spacing)
2671                 return true;
2672         return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
2673 }
2674
2675
2676 bool Paragraph::allowEmpty() const
2677 {
2678         if (d->layout_->keepempty)
2679                 return true;
2680         return d->inset_owner_ && d->inset_owner_->allowEmpty();
2681 }
2682
2683
2684 char_type Paragraph::transformChar(char_type c, pos_type pos) const
2685 {
2686         if (!Encodings::isArabicChar(c))
2687                 return c;
2688
2689         char_type prev_char = ' ';
2690         char_type next_char = ' ';
2691
2692         for (pos_type i = pos - 1; i >= 0; --i) {
2693                 char_type const par_char = d->text_[i];
2694                 if (!Encodings::isArabicComposeChar(par_char)) {
2695                         prev_char = par_char;
2696                         break;
2697                 }
2698         }
2699
2700         for (pos_type i = pos + 1, end = size(); i < end; ++i) {
2701                 char_type const par_char = d->text_[i];
2702                 if (!Encodings::isArabicComposeChar(par_char)) {
2703                         next_char = par_char;
2704                         break;
2705                 }
2706         }
2707
2708         if (Encodings::isArabicChar(next_char)) {
2709                 if (Encodings::isArabicChar(prev_char) &&
2710                         !Encodings::isArabicSpecialChar(prev_char))
2711                         return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
2712                 else
2713                         return Encodings::transformChar(c, Encodings::FORM_INITIAL);
2714         } else {
2715                 if (Encodings::isArabicChar(prev_char) &&
2716                         !Encodings::isArabicSpecialChar(prev_char))
2717                         return Encodings::transformChar(c, Encodings::FORM_FINAL);
2718                 else
2719                         return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
2720         }
2721 }
2722
2723
2724 int Paragraph::checkBiblio(Buffer const & buffer)
2725 {
2726         // FIXME From JS:
2727         // This is getting more and more a mess. ...We really should clean
2728         // up this bibitem issue for 1.6. See also bug 2743.
2729
2730         // Add bibitem insets if necessary
2731         if (d->layout_->labeltype != LABEL_BIBLIO)
2732                 return 0;
2733
2734         bool hasbibitem = !d->insetlist_.empty()
2735                 // Insist on it being in pos 0
2736                 && d->text_[0] == META_INSET
2737                 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
2738
2739         bool track_changes = buffer.params().trackChanges;
2740
2741         docstring oldkey;
2742         docstring oldlabel;
2743
2744         // remove a bibitem in pos != 0
2745         // restore it later in pos 0 if necessary
2746         // (e.g. if a user inserts contents _before_ the item)
2747         // we're assuming there's only one of these, which there
2748         // should be.
2749         int erasedInsetPosition = -1;
2750         InsetList::iterator it = d->insetlist_.begin();
2751         InsetList::iterator end = d->insetlist_.end();
2752         for (; it != end; ++it)
2753                 if (it->inset->lyxCode() == BIBITEM_CODE
2754                     && it->pos > 0) {
2755                         InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
2756                         oldkey = olditem->getParam("key");
2757                         oldlabel = olditem->getParam("label");
2758                         erasedInsetPosition = it->pos;
2759                         eraseChar(erasedInsetPosition, track_changes);
2760                         break;
2761         }
2762
2763         // There was an InsetBibitem at the beginning, and we didn't
2764         // have to erase one.
2765         if (hasbibitem && erasedInsetPosition < 0)
2766                         return 0;
2767
2768         // There was an InsetBibitem at the beginning and we did have to
2769         // erase one. So we give its properties to the beginning inset.
2770         if (hasbibitem) {
2771                 InsetBibitem * inset =
2772                         static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
2773                 if (!oldkey.empty())
2774                         inset->setParam("key", oldkey);
2775                 inset->setParam("label", oldlabel);
2776                 return -erasedInsetPosition;
2777         }
2778
2779         // There was no inset at the beginning, so we need to create one with
2780         // the key and label of the one we erased.
2781         InsetBibitem * inset = 
2782                 new InsetBibitem(buffer, InsetCommandParams(BIBITEM_CODE));
2783         // restore values of previously deleted item in this par.
2784         if (!oldkey.empty())
2785                 inset->setParam("key", oldkey);
2786         inset->setParam("label", oldlabel);
2787         insertInset(0, static_cast<Inset *>(inset),
2788                     Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
2789
2790         return 1;
2791 }
2792
2793
2794 void Paragraph::checkAuthors(AuthorList const & authorList)
2795 {
2796         d->changes_.checkAuthors(authorList);
2797 }
2798
2799
2800 bool Paragraph::isUnchanged(pos_type pos) const
2801 {
2802         return lookupChange(pos).type == Change::UNCHANGED;
2803 }
2804
2805
2806 bool Paragraph::isInserted(pos_type pos) const
2807 {
2808         return lookupChange(pos).type == Change::INSERTED;
2809 }
2810
2811
2812 bool Paragraph::isDeleted(pos_type pos) const
2813 {
2814         return lookupChange(pos).type == Change::DELETED;
2815 }
2816
2817
2818 InsetList const & Paragraph::insetList() const
2819 {
2820         return d->insetlist_;
2821 }
2822
2823
2824 void Paragraph::setBuffer(Buffer & b)
2825 {
2826         d->insetlist_.setBuffer(b);
2827 }
2828
2829
2830 Inset * Paragraph::releaseInset(pos_type pos)
2831 {
2832         Inset * inset = d->insetlist_.release(pos);
2833         /// does not honour change tracking!
2834         eraseChar(pos, false);
2835         return inset;
2836 }
2837
2838
2839 Inset * Paragraph::getInset(pos_type pos)
2840 {
2841         return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2842                  ? d->insetlist_.get(pos) : 0;
2843 }
2844
2845
2846 Inset const * Paragraph::getInset(pos_type pos) const
2847 {
2848         return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2849                  ? d->insetlist_.get(pos) : 0;
2850 }
2851
2852
2853 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
2854                 pos_type & right, TextCase action)
2855 {
2856         // process sequences of modified characters; in change
2857         // tracking mode, this approach results in much better
2858         // usability than changing case on a char-by-char basis
2859         docstring changes;
2860
2861         bool const trackChanges = bparams.trackChanges;
2862
2863         bool capitalize = true;
2864
2865         for (; pos < right; ++pos) {
2866                 char_type oldChar = d->text_[pos];
2867                 char_type newChar = oldChar;
2868
2869                 // ignore insets and don't play with deleted text!
2870                 if (oldChar != META_INSET && !isDeleted(pos)) {
2871                         switch (action) {
2872                                 case text_lowercase:
2873                                         newChar = lowercase(oldChar);
2874                                         break;
2875                                 case text_capitalization:
2876                                         if (capitalize) {
2877                                                 newChar = uppercase(oldChar);
2878                                                 capitalize = false;
2879                                         }
2880                                         break;
2881                                 case text_uppercase:
2882                                         newChar = uppercase(oldChar);
2883                                         break;
2884                         }
2885                 }
2886
2887                 if (isWordSeparator(pos) || isDeleted(pos)) {
2888                         // permit capitalization again
2889                         capitalize = true;
2890                 }
2891
2892                 if (oldChar != newChar) {
2893                         changes += newChar;
2894                         if (pos != right - 1)
2895                                 continue;
2896                         // step behind the changing area
2897                         pos++;
2898                 }
2899
2900                 int erasePos = pos - changes.size();
2901                 for (size_t i = 0; i < changes.size(); i++) {
2902                         insertChar(pos, changes[i],
2903                                    getFontSettings(bparams,
2904                                                    erasePos),
2905                                    trackChanges);
2906                         if (!eraseChar(erasePos, trackChanges)) {
2907                                 ++erasePos;
2908                                 ++pos; // advance
2909                                 ++right; // expand selection
2910                         }
2911                 }
2912                 changes.clear();
2913         }
2914 }
2915
2916
2917 bool Paragraph::find(docstring const & str, bool cs, bool mw,
2918                 pos_type pos, bool del) const
2919 {
2920         int const strsize = str.length();
2921         int i = 0;
2922         pos_type const parsize = d->text_.size();
2923         for (i = 0; pos + i < parsize; ++i) {
2924                 if (i >= strsize)
2925                         break;
2926                 if (cs && str[i] != d->text_[pos + i])
2927                         break;
2928                 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
2929                         break;
2930                 if (!del && isDeleted(pos + i))
2931                         break;
2932         }
2933
2934         if (i != strsize)
2935                 return false;
2936
2937         // if necessary, check whether string matches word
2938         if (mw) {
2939                 if (pos > 0 && !isWordSeparator(pos - 1))
2940                         return false;
2941                 if (pos + strsize < parsize
2942                         && !isWordSeparator(pos + strsize))
2943                         return false;
2944         }
2945
2946         return true;
2947 }
2948
2949
2950 char_type Paragraph::getChar(pos_type pos) const
2951 {
2952         return d->text_[pos];
2953 }
2954
2955
2956 pos_type Paragraph::size() const
2957 {
2958         return d->text_.size();
2959 }
2960
2961
2962 bool Paragraph::empty() const
2963 {
2964         return d->text_.empty();
2965 }
2966
2967
2968 bool Paragraph::isInset(pos_type pos) const
2969 {
2970         return d->text_[pos] == META_INSET;
2971 }
2972
2973
2974 bool Paragraph::isSeparator(pos_type pos) const
2975 {
2976         //FIXME: Are we sure this can be the only separator?
2977         return d->text_[pos] == ' ';
2978 }
2979
2980
2981 void Paragraph::deregisterWords()
2982 {
2983         Private::Words::const_iterator it;
2984         WordList & wl = theWordList();
2985         for (it = d->words_.begin(); it != d->words_.end(); ++it)
2986                 wl.remove(*it);
2987         d->words_.clear();
2988 }
2989
2990
2991 void Paragraph::locateWord(pos_type & from, pos_type & to,
2992         word_location const loc) const
2993 {
2994         switch (loc) {
2995         case WHOLE_WORD_STRICT:
2996                 if (from == 0 || from == size()
2997                     || isWordSeparator(from)
2998                     || isWordSeparator(from - 1)) {
2999                         to = from;
3000                         return;
3001                 }
3002                 // no break here, we go to the next
3003
3004         case WHOLE_WORD:
3005                 // If we are already at the beginning of a word, do nothing
3006                 if (!from || isWordSeparator(from - 1))
3007                         break;
3008                 // no break here, we go to the next
3009
3010         case PREVIOUS_WORD:
3011                 // always move the cursor to the beginning of previous word
3012                 while (from && !isWordSeparator(from - 1))
3013                         --from;
3014                 break;
3015         case NEXT_WORD:
3016                 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
3017                 break;
3018         case PARTIAL_WORD:
3019                 // no need to move the 'from' cursor
3020                 break;
3021         }
3022         to = from;
3023         while (to < size() && !isWordSeparator(to))
3024                 ++to;
3025 }
3026
3027
3028 void Paragraph::collectWords()
3029 {
3030         pos_type n = size();
3031         WordLangTuple wl;
3032         docstring_list suggestions;
3033         for (pos_type pos = 0; pos < n; ++pos) {
3034                 if (isWordSeparator(pos))
3035                         continue;
3036                 pos_type from = pos;
3037                 locateWord(from, pos, WHOLE_WORD);
3038                 if (pos - from >= 6) {
3039                         docstring word = asString(from, pos, AS_STR_NONE);
3040                         d->words_.insert(word);
3041                 }
3042                 if (lyxrc.spellcheck_continuously
3043                     && spellCheck(from, pos, wl, suggestions)) {
3044                         for (size_t i = 0; i != suggestions.size(); ++i)
3045                                 d->words_.insert(suggestions[i]);
3046                 }
3047         }
3048 }
3049
3050
3051 void Paragraph::registerWords()
3052 {
3053         Private::Words::const_iterator it;
3054         WordList & wl = theWordList();
3055         for (it = d->words_.begin(); it != d->words_.end(); ++it)
3056                 wl.insert(*it);
3057 }
3058
3059
3060 void Paragraph::updateWords()
3061 {
3062         deregisterWords();
3063         collectWords();
3064         registerWords();
3065 }
3066
3067
3068 bool Paragraph::spellCheck(pos_type & from, pos_type & to, WordLangTuple & wl,
3069         docstring_list & suggestions) const
3070 {
3071         SpellChecker * speller = theSpellChecker();
3072         if (!speller)
3073                 return false;
3074
3075         locateWord(from, to, WHOLE_WORD);
3076         if (from == to || from >= pos_type(d->text_.size()))
3077                 return false;
3078
3079         docstring word = asString(from, to, AS_STR_INSETS);
3080         string const lang_code = lyxrc.spellchecker_alt_lang.empty()
3081                 ? getFontSettings(d->inset_owner_->buffer().params(), from).language()->code()
3082                 : lyxrc.spellchecker_alt_lang;
3083         wl = WordLangTuple(word, lang_code);
3084         SpellChecker::Result res = speller->check(wl);
3085         // Just ignore any error that the spellchecker reports.
3086         // FIXME: we should through out an exception and catch it in the GUI to
3087         // display the error.
3088         if (!speller->error().empty())
3089                 return false;
3090
3091         bool const misspelled = res != SpellChecker::OK
3092                 && res != SpellChecker::IGNORED_WORD;
3093
3094         if (lyxrc.spellcheck_continuously)
3095                 d->fontlist_.setMisspelled(from, to, misspelled);
3096
3097         if (misspelled) {
3098                 while (!(word = speller->nextMiss()).empty())
3099                         suggestions.push_back(word);
3100         }
3101         return misspelled;
3102 }
3103
3104
3105 bool Paragraph::isMisspelled(pos_type pos) const
3106 {
3107         pos_type from = pos;
3108         pos_type to = pos;
3109         WordLangTuple wl;
3110         docstring_list suggestions;
3111         return spellCheck(from, to, wl, suggestions);
3112 }
3113
3114
3115 } // namespace lyx