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