]> git.lyx.org Git - lyx.git/blob - src/paragraph_pimpl.C
Partial fix bug 2092: branches not propagated to child documents
[lyx.git] / src / paragraph_pimpl.C
1 /**
2  * \file paragraph_pimpl.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Jean-Marc Lasgouttes
8  * \author John Levon
9  * \author André Pönitz
10  *
11  * Full author contact details are available in file CREDITS.
12  */
13
14 #include <config.h>
15
16 #include "paragraph_pimpl.h"
17
18 #include "bufferparams.h"
19 #include "debug.h"
20 #include "encoding.h"
21 #include "language.h"
22 #include "LaTeXFeatures.h"
23 #include "LColor.h"
24 #include "lyxlength.h"
25 #include "lyxrc.h"
26 #include "outputparams.h"
27 #include "texrow.h"
28
29 #include <boost/next_prior.hpp>
30
31 using lyx::pos_type;
32
33 using std::endl;
34 using std::upper_bound;
35 using std::lower_bound;
36 using std::string;
37 using std::ostream;
38
39
40 // Initialization of the counter for the paragraph id's,
41 unsigned int Paragraph::Pimpl::paragraph_id = 0;
42
43 namespace {
44
45 struct special_phrase {
46         string phrase;
47         string macro;
48         bool builtin;
49 };
50
51 special_phrase special_phrases[] = {
52         { "LyX", "\\LyX{}", false },
53         { "TeX", "\\TeX{}", true },
54         { "LaTeX2e", "\\LaTeXe{}", true },
55         { "LaTeX", "\\LaTeX{}", true },
56 };
57
58 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
59
60 } // namespace anon
61
62
63 Paragraph::Pimpl::Pimpl(Paragraph * owner)
64         : owner_(owner)
65 {
66         inset_owner = 0;
67         id_ = paragraph_id++;
68 }
69
70
71 Paragraph::Pimpl::Pimpl(Pimpl const & p, Paragraph * owner)
72         : params(p.params), owner_(owner)
73 {
74         inset_owner = p.inset_owner;
75         fontlist = p.fontlist;
76         id_ = paragraph_id++;
77
78         if (p.tracking())
79                 changes_.reset(new Changes(*p.changes_.get()));
80 }
81
82
83 void Paragraph::Pimpl::setContentsFromPar(Paragraph const & par)
84 {
85         owner_->text_ = par.text_;
86         if (par.pimpl_->tracking()) {
87                 changes_.reset(new Changes(*(par.pimpl_->changes_.get())));
88         }
89 }
90
91
92 void Paragraph::Pimpl::trackChanges(Change::Type type)
93 {
94         if (tracking()) {
95                 lyxerr[Debug::CHANGES] << "already tracking for par " << id_ << endl;
96                 return;
97         }
98
99         lyxerr[Debug::CHANGES] << "track changes for par "
100                 << id_ << " type " << type << endl;
101         changes_.reset(new Changes(type));
102         changes_->set(type, 0, size());
103 }
104
105
106 void Paragraph::Pimpl::untrackChanges()
107 {
108         changes_.reset(0);
109 }
110
111
112 void Paragraph::Pimpl::cleanChanges()
113 {
114         // if we're not tracking, we don't want to reset...
115         if (!tracking())
116                 return;
117
118         changes_.reset(new Changes(Change::INSERTED));
119         changes_->set(Change::INSERTED, 0, size());
120 }
121
122
123 bool Paragraph::Pimpl::isChanged(pos_type start, pos_type end) const
124 {
125         if (!tracking())
126                 return false;
127
128         return changes_->isChange(start, end);
129 }
130
131
132 bool Paragraph::Pimpl::isChangeEdited(pos_type start, pos_type end) const
133 {
134         if (!tracking())
135                 return false;
136
137         return changes_->isChangeEdited(start, end);
138 }
139
140
141 void Paragraph::Pimpl::setChange(pos_type pos, Change::Type type)
142 {
143         if (!tracking())
144                 return;
145
146         changes_->set(type, pos);
147 }
148
149
150 Change::Type Paragraph::Pimpl::lookupChange(pos_type pos) const
151 {
152         if (!tracking())
153                 return Change::UNCHANGED;
154
155         return changes_->lookup(pos);
156 }
157
158
159 Change const Paragraph::Pimpl::lookupChangeFull(pos_type pos) const
160 {
161         if (!tracking())
162                 return Change(Change::UNCHANGED);
163
164         return changes_->lookupFull(pos);
165 }
166
167
168 void Paragraph::Pimpl::markErased(bool erased)
169 {
170         BOOST_ASSERT(tracking());
171
172         if (erased) {
173                 erase(0, size());
174         } else {
175                 for (pos_type i = 0; i < size(); ++i) {
176                         changes_->set(Change::UNCHANGED, i);
177                         if (owner_->isInset(i))
178                                 owner_->getInset(i)->markErased(false);
179                 }
180         }
181 }
182
183
184 void Paragraph::Pimpl::acceptChange(pos_type start, pos_type end)
185 {
186         if (!tracking())
187                 return;
188
189         if (!size()) {
190                 changes_.reset(new Changes(Change::UNCHANGED));
191                 return;
192         }
193
194         lyxerr[Debug::CHANGES] << "acceptchange" << endl;
195         pos_type i = start;
196
197         for (; i < end; ++i) {
198                 switch (lookupChange(i)) {
199                         case Change::UNCHANGED:
200                                 break;
201
202                         case Change::INSERTED:
203                                 changes_->set(Change::UNCHANGED, i);
204                                 break;
205
206                         case Change::DELETED:
207                                 eraseIntern(i);
208                                 changes_->erase(i);
209                                 --end;
210                                 --i;
211                                 break;
212                 }
213         }
214
215         lyxerr[Debug::CHANGES] << "endacceptchange" << endl;
216         changes_->reset(Change::UNCHANGED);
217 }
218
219
220 void Paragraph::Pimpl::rejectChange(pos_type start, pos_type end)
221 {
222         if (!tracking())
223                 return;
224
225         if (!size()) {
226                 changes_.reset(new Changes(Change::UNCHANGED));
227                 return;
228         }
229
230         pos_type i = start;
231
232         for (; i < end; ++i) {
233                 switch (lookupChange(i)) {
234                         case Change::UNCHANGED:
235                                 break;
236
237                         case Change::INSERTED:
238                                 eraseIntern(i);
239                                 changes_->erase(i);
240                                 --end;
241                                 --i;
242                                 break;
243
244                         case Change::DELETED:
245                                 changes_->set(Change::UNCHANGED, i);
246                                 if (owner_->isInset(i))
247                                         owner_->getInset(i)->markErased(false);
248                                 break;
249                 }
250         }
251         changes_->reset(Change::UNCHANGED);
252 }
253
254
255 Paragraph::value_type Paragraph::Pimpl::getChar(pos_type pos) const
256 {
257         return owner_->getChar(pos);
258 }
259
260
261 void Paragraph::Pimpl::insertChar(pos_type pos, value_type c, Change change)
262 {
263         BOOST_ASSERT(pos <= size());
264
265         if (tracking()) {
266                 changes_->record(change, pos);
267         }
268
269         // This is actually very common when parsing buffers (and
270         // maybe inserting ascii text)
271         if (pos == size()) {
272                 // when appending characters, no need to update tables
273                 owner_->text_.push_back(c);
274                 return;
275         }
276
277         owner_->text_.insert(owner_->text_.begin() + pos, c);
278
279         // Update the font table.
280         FontTable search_font(pos, LyXFont());
281         for (FontList::iterator it = lower_bound(fontlist.begin(),
282                                                       fontlist.end(),
283                                                       search_font, matchFT());
284              it != fontlist.end(); ++it)
285         {
286                 it->pos(it->pos() + 1);
287         }
288
289         // Update the insets
290         owner_->insetlist.increasePosAfterPos(pos);
291 }
292
293
294 void Paragraph::Pimpl::insertInset(pos_type pos,
295                                    InsetBase * inset, Change change)
296 {
297         BOOST_ASSERT(inset);
298         BOOST_ASSERT(pos <= size());
299
300         insertChar(pos, META_INSET, change);
301         BOOST_ASSERT(owner_->text_[pos] == META_INSET);
302
303         // Add a new entry in the insetlist.
304         owner_->insetlist.insert(inset, pos);
305 }
306
307
308 void Paragraph::Pimpl::eraseIntern(pos_type pos)
309 {
310         // if it is an inset, delete the inset entry
311         if (owner_->text_[pos] == Paragraph::META_INSET) {
312                 owner_->insetlist.erase(pos);
313         }
314
315         owner_->text_.erase(owner_->text_.begin() + pos);
316
317         // Erase entries in the tables.
318         FontTable search_font(pos, LyXFont());
319
320         FontList::iterator it =
321                 lower_bound(fontlist.begin(),
322                             fontlist.end(),
323                             search_font, matchFT());
324         if (it != fontlist.end() && it->pos() == pos &&
325             (pos == 0 ||
326              (it != fontlist.begin()
327               && boost::prior(it)->pos() == pos - 1))) {
328                 // If it is a multi-character font
329                 // entry, we just make it smaller
330                 // (see update below), otherwise we
331                 // should delete it.
332                 unsigned int const i = it - fontlist.begin();
333                 fontlist.erase(fontlist.begin() + i);
334                 it = fontlist.begin() + i;
335                 if (i > 0 && i < fontlist.size() &&
336                     fontlist[i - 1].font() == fontlist[i].font()) {
337                         fontlist.erase(fontlist.begin() + i - 1);
338                         it = fontlist.begin() + i - 1;
339                 }
340         }
341
342         // Update all other entries.
343         FontList::iterator fend = fontlist.end();
344         for (; it != fend; ++it)
345                 it->pos(it->pos() - 1);
346
347         // Update the insetlist.
348         owner_->insetlist.decreasePosAfterPos(pos);
349 }
350
351
352 bool Paragraph::Pimpl::erase(pos_type pos)
353 {
354         BOOST_ASSERT(pos < size());
355
356         if (tracking()) {
357                 Change::Type changetype(changes_->lookup(pos));
358                 changes_->record(Change(Change::DELETED), pos);
359
360                 // only allow the actual removal if it was /new/ text
361                 if (changetype != Change::INSERTED) {
362                         if (owner_->isInset(pos))
363                                 owner_->getInset(pos)->markErased(true);
364                         return false;
365                 }
366         }
367
368         eraseIntern(pos);
369         return true;
370 }
371
372
373 int Paragraph::Pimpl::erase(pos_type start, pos_type end)
374 {
375         pos_type i = start;
376         for (pos_type count = end - start; count; --count) {
377                 if (!erase(i))
378                         ++i;
379         }
380         return end - i;
381 }
382
383
384 void Paragraph::Pimpl::simpleTeXBlanks(ostream & os, TexRow & texrow,
385                                        pos_type const i,
386                                        unsigned int & column,
387                                        LyXFont const & font,
388                                        LyXLayout const & style)
389 {
390         if (style.pass_thru)
391                 return;
392
393         if (column > lyxrc.ascii_linelen
394             && i
395             && getChar(i - 1) != ' '
396             && (i < size() - 1)
397             // same in FreeSpacing mode
398             && !owner_->isFreeSpacing()
399             // In typewriter mode, we want to avoid
400             // ! . ? : at the end of a line
401             && !(font.family() == LyXFont::TYPEWRITER_FAMILY
402                  && (getChar(i - 1) == '.'
403                      || getChar(i - 1) == '?'
404                      || getChar(i - 1) == ':'
405                      || getChar(i - 1) == '!'))) {
406                 os << '\n';
407                 texrow.newline();
408                 texrow.start(owner_->id(), i + 1);
409                 column = 0;
410         } else if (style.free_spacing) {
411                 os << '~';
412         } else {
413                 os << ' ';
414         }
415 }
416
417
418 bool Paragraph::Pimpl::isTextAt(string const & str, pos_type pos) const
419 {
420         pos_type const len = str.length();
421
422         // is the paragraph large enough?
423         if (pos + len > size())
424                 return false;
425
426         // does the wanted text start at point?
427         for (string::size_type i = 0; i < str.length(); ++i) {
428                 if (str[i] != owner_->text_[pos + i])
429                         return false;
430         }
431
432         // is there a font change in middle of the word?
433         FontList::const_iterator cit = fontlist.begin();
434         FontList::const_iterator end = fontlist.end();
435         for (; cit != end; ++cit) {
436                 if (cit->pos() >= pos)
437                         break;
438         }
439         if (cit != end && pos + len - 1 > cit->pos())
440                 return false;
441
442         return true;
443 }
444
445
446 void Paragraph::Pimpl::simpleTeXSpecialChars(Buffer const & buf,
447                                              BufferParams const & bparams,
448                                              ostream & os,
449                                              TexRow & texrow,
450                                              OutputParams const & runparams,
451                                              LyXFont & font,
452                                              LyXFont & running_font,
453                                              LyXFont & basefont,
454                                              LyXFont const & outerfont,
455                                              bool & open_font,
456                                              Change::Type & running_change,
457                                              LyXLayout const & style,
458                                              pos_type & i,
459                                              unsigned int & column,
460                                              value_type const c)
461 {
462         if (style.pass_thru) {
463                 if (c != Paragraph::META_INSET) {
464                         if (c != '\0')
465                                 os << c;
466                 } else {
467                         owner_->getInset(i)->plaintext(buf, os, runparams);
468                 }
469                 return;
470         }
471
472         // Two major modes:  LaTeX or plain
473         // Handle here those cases common to both modes
474         // and then split to handle the two modes separately.
475         switch (c) {
476         case Paragraph::META_INSET: {
477                 InsetBase * inset = owner_->getInset(i);
478
479                 // FIXME: remove this check
480                 if (!inset)
481                         break;
482
483                 // FIXME: move this to InsetNewline::latex
484                 if (inset->lyxCode() == InsetBase::NEWLINE_CODE) {
485                         // newlines are handled differently here than
486                         // the default in simpleTeXSpecialChars().
487                         if (!style.newline_allowed) {
488                                 os << '\n';
489                         } else {
490                                 if (open_font) {
491                                         column += running_font.latexWriteEndChanges(os, basefont, basefont);
492                                         open_font = false;
493                                 }
494                                 basefont = owner_->getLayoutFont(bparams, outerfont);
495                                 running_font = basefont;
496
497                                 if (font.family() == LyXFont::TYPEWRITER_FAMILY)
498                                         os << '~';
499
500                                 if (runparams.moving_arg)
501                                         os << "\\protect ";
502
503                                 os << "\\\\\n";
504                         }
505                         texrow.newline();
506                         texrow.start(owner_->id(), i + 1);
507                         column = 0;
508                         break;
509                 }
510
511                 // output change tracking marks only if desired,
512                 // if dvipost is installed,
513                 // and with dvi/ps (other formats don't work)
514                 LaTeXFeatures features(buf, bparams, runparams.nice);
515                 bool const output = bparams.output_changes
516                         && runparams.flavor == OutputParams::LATEX
517                         && features.isAvailable("dvipost");
518
519                 if (inset->isTextInset()) {
520                         column += Changes::latexMarkChange(os, running_change,
521                                 Change::UNCHANGED, output);
522                         running_change = Change::UNCHANGED;
523                 }
524
525                 bool close = false;
526                 ostream::pos_type const len = os.tellp();
527
528                 if ((inset->lyxCode() == InsetBase::GRAPHICS_CODE
529                      || inset->lyxCode() == InsetBase::MATH_CODE
530                      || inset->lyxCode() == InsetBase::URL_CODE)
531                     && running_font.isRightToLeft()) {
532                         os << "\\L{";
533                         close = true;
534                 }
535
536 #ifdef WITH_WARNINGS
537 #warning Bug: we can have an empty font change here!
538 // if there has just been a font change, we are going to close it
539 // right now, which means stupid latex code like \textsf{}. AFAIK,
540 // this does not harm dvi output. A minor bug, thus (JMarc)
541 #endif
542                 // some insets cannot be inside a font change command
543                 if (open_font && inset->noFontChange()) {
544                         column +=running_font.
545                                 latexWriteEndChanges(os,
546                                                      basefont,
547                                                      basefont);
548                         open_font = false;
549                         basefont = owner_->getLayoutFont(bparams, outerfont);
550                         running_font = basefont;
551                 }
552
553                 int tmp = inset->latex(buf, os, runparams);
554
555                 if (close)
556                         os << '}';
557
558                 if (tmp) {
559                         for (int j = 0; j < tmp; ++j) {
560                                 texrow.newline();
561                         }
562                         texrow.start(owner_->id(), i + 1);
563                         column = 0;
564                 } else {
565                         column += os.tellp() - len;
566                 }
567         }
568         break;
569
570         default:
571                 // And now for the special cases within each mode
572
573                 switch (c) {
574                 case '\\':
575                         os << "\\textbackslash{}";
576                         column += 15;
577                         break;
578
579                 case '±': case '²': case '³':
580                 case '×': case '÷': case '¹':
581                 case '¬': case 'µ':
582                         if ((bparams.inputenc == "latin1" ||
583                              bparams.inputenc == "latin9") ||
584                             (bparams.inputenc == "auto" &&
585                              (font.language()->encoding()->LatexName()
586                               == "latin1" ||
587                               font.language()->encoding()->LatexName()
588                               == "latin9"))) {
589                                 os << "\\ensuremath{"
590                                    << c
591                                    << '}';
592                                 column += 13;
593                         } else {
594                                 os << c;
595                         }
596                         break;
597
598                 case '|': case '<': case '>':
599                         // In T1 encoding, these characters exist
600                         if (lyxrc.fontenc == "T1") {
601                                 os << c;
602                                 //... but we should avoid ligatures
603                                 if ((c == '>' || c == '<')
604                                     && i <= size() - 2
605                                     && getChar(i + 1) == c) {
606                                         //os << "\\textcompwordmark{}";
607                                         // Jean-Marc, have a look at
608                                         // this. I think this works
609                                         // equally well:
610                                         os << "\\,{}";
611                                         // Lgb
612                                         column += 19;
613                                 }
614                                 break;
615                         }
616                         // Typewriter font also has them
617                         if (font.family() == LyXFont::TYPEWRITER_FAMILY) {
618                                 os << c;
619                                 break;
620                         }
621                         // Otherwise, we use what LaTeX
622                         // provides us.
623                         switch (c) {
624                         case '<':
625                                 os << "\\textless{}";
626                                 column += 10;
627                                 break;
628                         case '>':
629                                 os << "\\textgreater{}";
630                                 column += 13;
631                                 break;
632                         case '|':
633                                 os << "\\textbar{}";
634                                 column += 9;
635                                 break;
636                         }
637                         break;
638
639                 case '-': // "--" in Typewriter mode -> "-{}-"
640                         if (i <= size() - 2
641                             && getChar(i + 1) == '-'
642                             && font.family() == LyXFont::TYPEWRITER_FAMILY) {
643                                 os << "-{}";
644                                 column += 2;
645                         } else {
646                                 os << '-';
647                         }
648                         break;
649
650                 case '\"':
651                         os << "\\char`\\\"{}";
652                         column += 9;
653                         break;
654
655                 case '£':
656                         if (bparams.inputenc == "default") {
657                                 os << "\\pounds{}";
658                                 column += 8;
659                         } else {
660                                 os << c;
661                         }
662                         break;
663
664                 case '$': case '&':
665                 case '%': case '#': case '{':
666                 case '}': case '_':
667                         os << '\\' << c;
668                         column += 1;
669                         break;
670
671                 case '~':
672                         os << "\\textasciitilde{}";
673                         column += 16;
674                         break;
675
676                 case '^':
677                         os << "\\textasciicircum{}";
678                         column += 17;
679                         break;
680
681                 case '*': case '[':
682                         // avoid being mistaken for optional arguments
683                         os << '{' << c << '}';
684                         column += 2;
685                         break;
686
687                 case ' ':
688                         // Blanks are printed before font switching.
689                         // Sure? I am not! (try nice-latex)
690                         // I am sure it's correct. LyX might be smarter
691                         // in the future, but for now, nothing wrong is
692                         // written. (Asger)
693                         break;
694
695                 default:
696
697                         // I assume this is hack treating typewriter as verbatim
698                         if (font.family() == LyXFont::TYPEWRITER_FAMILY) {
699                                 if (c != '\0') {
700                                         os << c;
701                                 }
702                                 break;
703                         }
704
705                         // LyX, LaTeX etc.
706
707                         // FIXME: if we have "LaTeX" with a font
708                         // change in the middle (before the 'T', then
709                         // the "TeX" part is still special cased.
710                         // Really we should only operate this on
711                         // "words" for some definition of word
712
713                         size_t pnr = 0;
714
715                         for (; pnr < phrases_nr; ++pnr) {
716                                 if (isTextAt(special_phrases[pnr].phrase, i)) {
717                                         os << special_phrases[pnr].macro;
718                                         i += special_phrases[pnr].phrase.length() - 1;
719                                         column += special_phrases[pnr].macro.length() - 1;
720                                         break;
721                                 }
722                         }
723
724                         if (pnr == phrases_nr && c != '\0') {
725                                 os << c;
726                         }
727                         break;
728                 }
729         }
730 }
731
732
733 void Paragraph::Pimpl::validate(LaTeXFeatures & features,
734                                 LyXLayout const & layout) const
735 {
736         BufferParams const & bparams = features.bufferParams();
737
738         // check the params.
739         if (!params.spacing().isDefault())
740                 features.require("setspace");
741
742         // then the layouts
743         features.useLayout(layout.name());
744
745         // then the fonts
746         Language const * doc_language = bparams.language;
747
748         FontList::const_iterator fcit = fontlist.begin();
749         FontList::const_iterator fend = fontlist.end();
750         for (; fcit != fend; ++fcit) {
751                 if (fcit->font().noun() == LyXFont::ON) {
752                         lyxerr[Debug::LATEX] << "font.noun: "
753                                              << fcit->font().noun()
754                                              << endl;
755                         features.require("noun");
756                         lyxerr[Debug::LATEX] << "Noun enabled. Font: "
757                                              << fcit->font().stateText(0)
758                                              << endl;
759                 }
760                 switch (fcit->font().color()) {
761                 case LColor::none:
762                 case LColor::inherit:
763                 case LColor::ignore:
764                         // probably we should put here all interface colors used for
765                         // font displaying! For now I just add this ones I know of (Jug)
766                 case LColor::latex:
767                 case LColor::note:
768                         break;
769                 default:
770                         features.require("color");
771                         lyxerr[Debug::LATEX] << "Color enabled. Font: "
772                                              << fcit->font().stateText(0)
773                                              << endl;
774                 }
775
776                 Language const * language = fcit->font().language();
777                 if (language->babel() != doc_language->babel() &&
778                     language != ignore_language &&
779                     language != latex_language)
780                 {
781                         features.useLanguage(language);
782                         lyxerr[Debug::LATEX] << "Found language "
783                                              << language->babel() << endl;
784                 }
785         }
786
787         if (!params.leftIndent().zero())
788                 features.require("ParagraphLeftIndent");
789
790         // then the insets
791         InsetList::const_iterator icit = owner_->insetlist.begin();
792         InsetList::const_iterator iend = owner_->insetlist.end();
793         for (; icit != iend; ++icit) {
794                 if (icit->inset) {
795                         icit->inset->validate(features);
796                         if (layout.needprotect &&
797                             icit->inset->lyxCode() == InsetBase::FOOT_CODE)
798                                 features.require("NeedLyXFootnoteCode");
799                 }
800         }
801
802         // then the contents
803         for (pos_type i = 0; i < size() ; ++i) {
804                 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
805                         if (!special_phrases[pnr].builtin
806                             && isTextAt(special_phrases[pnr].phrase, i)) {
807                                 features.require(special_phrases[pnr].phrase);
808                                 break;
809                         }
810                 }
811         }
812 }