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