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