]> git.lyx.org Git - lyx.git/blob - src/paragraph_pimpl.C
Use 'assign' as the name for the operation that opens/closes branch
[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
30 using lyx::pos_type;
31
32 using std::endl;
33 using std::upper_bound;
34 using std::lower_bound;
35 using std::string;
36 using std::ostream;
37
38
39 // Initialize static member.
40 ShareContainer<LyXFont> Paragraph::Pimpl::FontTable::container;
41 // Initialization of the counter for the paragraph id's,
42 unsigned int Paragraph::Pimpl::paragraph_id = 0;
43
44 namespace {
45
46 struct special_phrase {
47         string phrase;
48         string macro;
49         bool builtin;
50 };
51
52 special_phrase special_phrases[] = {
53         { "LyX", "\\LyX{}", false },
54         { "TeX", "\\TeX{}", true },
55         { "LaTeX2e", "\\LaTeXe{}", true },
56         { "LaTeX", "\\LaTeX{}", true },
57 };
58
59 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
60
61 } // namespace anon
62
63
64 Paragraph::Pimpl::Pimpl(Paragraph * owner)
65         : owner_(owner)
66 {
67         inset_owner = 0;
68         id_ = paragraph_id++;
69 }
70
71
72 Paragraph::Pimpl::Pimpl(Pimpl const & p, Paragraph * owner)
73         : params(p.params), owner_(owner)
74 {
75         inset_owner = p.inset_owner;
76         fontlist = p.fontlist;
77         id_ = paragraph_id++;
78
79         if (p.tracking())
80                 changes_.reset(new Changes(*p.changes_.get()));
81 }
82
83
84 void Paragraph::Pimpl::setContentsFromPar(Paragraph const & par)
85 {
86         owner_->text_ = par.text_;
87         if (par.pimpl_->tracking()) {
88                 changes_.reset(new Changes(*(par.pimpl_->changes_.get())));
89         }
90 }
91
92
93 void Paragraph::Pimpl::trackChanges(Change::Type type)
94 {
95         if (tracking()) {
96                 lyxerr[Debug::CHANGES] << "already tracking for par " << id_ << endl;
97                 return;
98         }
99
100         lyxerr[Debug::CHANGES] << "track changes for par "
101                 << id_ << " type " << type << endl;
102         changes_.reset(new Changes(type));
103         changes_->set(type, 0, size());
104 }
105
106
107 void Paragraph::Pimpl::untrackChanges()
108 {
109         changes_.reset(0);
110 }
111
112
113 void Paragraph::Pimpl::cleanChanges()
114 {
115         // if we're not tracking, we don't want to reset...
116         if (!tracking())
117                 return;
118
119         changes_.reset(new Changes(Change::INSERTED));
120         changes_->set(Change::INSERTED, 0, size());
121 }
122
123
124 bool Paragraph::Pimpl::isChanged(pos_type start, pos_type end) const
125 {
126         if (!tracking())
127                 return false;
128
129         return changes_->isChange(start, end);
130 }
131
132
133 bool Paragraph::Pimpl::isChangeEdited(pos_type start, pos_type end) const
134 {
135         if (!tracking())
136                 return false;
137
138         return changes_->isChangeEdited(start, end);
139 }
140
141
142 void Paragraph::Pimpl::setChange(pos_type pos, Change::Type type)
143 {
144         if (!tracking())
145                 return;
146
147         changes_->set(type, pos);
148 }
149
150
151 Change::Type Paragraph::Pimpl::lookupChange(pos_type pos) const
152 {
153         if (!tracking())
154                 return Change::UNCHANGED;
155
156         return changes_->lookup(pos);
157 }
158
159
160 Change const Paragraph::Pimpl::lookupChangeFull(pos_type pos) const
161 {
162         if (!tracking())
163                 return Change(Change::UNCHANGED);
164
165         return changes_->lookupFull(pos);
166 }
167
168
169 void Paragraph::Pimpl::markErased()
170 {
171         BOOST_ASSERT(tracking());
172
173         // FIXME: we should actually remove INSERTED chars.
174         // difficult because owning insettexts/tabulars need
175         // to update themselves when rows etc. change
176         changes_->set(Change::DELETED, 0, size());
177         changes_->reset(Change::DELETED);
178 }
179
180
181 void Paragraph::Pimpl::acceptChange(pos_type start, pos_type end)
182 {
183         if (!tracking())
184                 return;
185
186         if (!size()) {
187                 changes_.reset(new Changes(Change::UNCHANGED));
188                 return;
189         }
190
191         lyxerr << "acceptchange" << endl;
192         pos_type i = start;
193
194         for (; i < end; ++i) {
195                 switch (lookupChange(i)) {
196                         case Change::UNCHANGED:
197                                 break;
198
199                         case Change::INSERTED:
200                                 changes_->set(Change::UNCHANGED, i);
201                                 break;
202
203                         case Change::DELETED:
204                                 eraseIntern(i);
205                                 changes_->erase(i);
206                                 --end;
207                                 --i;
208                                 break;
209                 }
210         }
211
212         lyxerr << "endacceptchange" << endl;
213         changes_->reset(Change::UNCHANGED);
214 }
215
216
217 void Paragraph::Pimpl::rejectChange(pos_type start, pos_type end)
218 {
219         if (!tracking())
220                 return;
221
222         if (!size()) {
223                 changes_.reset(new Changes(Change::UNCHANGED));
224                 return;
225         }
226
227         pos_type i = start;
228
229         for (; i < end; ++i) {
230                 switch (lookupChange(i)) {
231                         case Change::UNCHANGED:
232                                 break;
233
234                         case Change::INSERTED:
235                                 eraseIntern(i);
236                                 changes_->erase(i);
237                                 --end;
238                                 --i;
239                                 break;
240
241                         case Change::DELETED:
242                                 changes_->set(Change::UNCHANGED, i);
243                                 break;
244                 }
245         }
246         changes_->reset(Change::UNCHANGED);
247 }
248
249
250 Paragraph::value_type Paragraph::Pimpl::getChar(pos_type pos) const
251 {
252         return owner_->getChar(pos);
253 }
254
255
256 void Paragraph::Pimpl::insertChar(pos_type pos, value_type c,
257                                   LyXFont const & font, Change change)
258 {
259         BOOST_ASSERT(pos <= size());
260
261         if (tracking()) {
262                 changes_->record(change, pos);
263         }
264
265         // This is actually very common when parsing buffers (and
266         // maybe inserting ascii text)
267         if (pos == size()) {
268                 // when appending characters, no need to update tables
269                 owner_->text_.push_back(c);
270                 owner_->setFont(pos, font);
271                 return;
272         }
273
274         owner_->text_.insert(owner_->text_.begin() + pos, c);
275
276         // Update the font table.
277         FontTable search_font(pos, LyXFont());
278         for (FontList::iterator it = lower_bound(fontlist.begin(),
279                                                       fontlist.end(),
280                                                       search_font, matchFT());
281              it != fontlist.end(); ++it)
282         {
283                 it->pos(it->pos() + 1);
284         }
285
286         // Update the insets
287         owner_->insetlist.increasePosAfterPos(pos);
288
289         owner_->setFont(pos, font);
290 }
291
292
293 void Paragraph::Pimpl::insertInset(pos_type pos,
294                                    InsetBase * inset, LyXFont const & font, Change change)
295 {
296         BOOST_ASSERT(inset);
297         BOOST_ASSERT(pos <= size());
298
299         insertChar(pos, META_INSET, font, change);
300         BOOST_ASSERT(owner_->text_[pos] == META_INSET);
301
302         // Add a new entry in the insetlist.
303         owner_->insetlist.insert(inset, pos);
304 }
305
306
307 void Paragraph::Pimpl::eraseIntern(pos_type pos)
308 {
309         // if it is an inset, delete the inset entry
310         if (owner_->text_[pos] == Paragraph::META_INSET) {
311                 owner_->insetlist.erase(pos);
312         }
313
314         owner_->text_.erase(owner_->text_.begin() + pos);
315
316         // Erase entries in the tables.
317         FontTable search_font(pos, LyXFont());
318
319         FontList::iterator it =
320                 lower_bound(fontlist.begin(),
321                             fontlist.end(),
322                             search_font, matchFT());
323         if (it != fontlist.end() && it->pos() == pos &&
324             (pos == 0 ||
325              (it != fontlist.begin()
326               && boost::prior(it)->pos() == pos - 1))) {
327                 // If it is a multi-character font
328                 // entry, we just make it smaller
329                 // (see update below), otherwise we
330                 // should delete it.
331                 unsigned int const i = it - fontlist.begin();
332                 fontlist.erase(fontlist.begin() + i);
333                 it = fontlist.begin() + i;
334                 if (i > 0 && i < fontlist.size() &&
335                     fontlist[i - 1].font() == fontlist[i].font()) {
336                         fontlist.erase(fontlist.begin() + i - 1);
337                         it = fontlist.begin() + i - 1;
338                 }
339         }
340
341         // Update all other entries.
342         FontList::iterator fend = fontlist.end();
343         for (; it != fend; ++it)
344                 it->pos(it->pos() - 1);
345
346         // Update the insetlist.
347         owner_->insetlist.decreasePosAfterPos(pos);
348 }
349
350
351 bool Paragraph::Pimpl::erase(pos_type pos)
352 {
353         BOOST_ASSERT(pos < size());
354
355         if (tracking()) {
356                 Change::Type changetype(changes_->lookup(pos));
357                 changes_->record(Change(Change::DELETED), pos);
358
359                 // only allow the actual removal if it was /new/ text
360                 if (changetype != Change::INSERTED) {
361                         if (owner_->text_[pos] == Paragraph::META_INSET) {
362                                 owner_->getInset(pos)->markErased();
363                         }
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                 if (inset->isTextInset()) {
512                         column += Changes::latexMarkChange(os, running_change,
513                                 Change::UNCHANGED);
514                         running_change = Change::UNCHANGED;
515                 }
516
517                 bool close = false;
518                 ostream::pos_type const len = os.tellp();
519
520                 if ((inset->lyxCode() == InsetBase::GRAPHICS_CODE
521                      || inset->lyxCode() == InsetBase::MATH_CODE
522                      || inset->lyxCode() == InsetBase::URL_CODE)
523                     && running_font.isRightToLeft()) {
524                         os << "\\L{";
525                         close = true;
526                 }
527
528 #ifdef WITH_WARNINGS
529 #warning Bug: we can have an empty font change here!
530 // if there has just been a font change, we are going to close it
531 // right now, which means stupid latex code like \textsf{}. AFAIK,
532 // this does not harm dvi output. A minor bug, thus (JMarc)
533 #endif
534                 // some insets cannot be inside a font change command
535                 if (open_font && inset->noFontChange()) {
536                         column +=running_font.
537                                 latexWriteEndChanges(os,
538                                                      basefont,
539                                                      basefont);
540                         open_font = false;
541                         basefont = owner_->getLayoutFont(bparams, outerfont);
542                         running_font = basefont;
543                 }
544
545                 int tmp = inset->latex(buf, os, runparams);
546
547                 if (close)
548                         os << '}';
549
550                 if (tmp) {
551                         for (int j = 0; j < tmp; ++j) {
552                                 texrow.newline();
553                         }
554                         texrow.start(owner_->id(), i + 1);
555                         column = 0;
556                 } else {
557                         column += os.tellp() - len;
558                 }
559         }
560         break;
561
562         default:
563                 // And now for the special cases within each mode
564
565                 switch (c) {
566                 case '\\':
567                         os << "\\textbackslash{}";
568                         column += 15;
569                         break;
570
571                 case '±': case '²': case '³':
572                 case '×': case '÷': case '¹':
573                 case '¬': case 'µ':
574                         if ((bparams.inputenc == "latin1" ||
575                              bparams.inputenc == "latin9") ||
576                             (bparams.inputenc == "auto" &&
577                              (font.language()->encoding()->LatexName()
578                               == "latin1" ||
579                               font.language()->encoding()->LatexName()
580                               == "latin9"))) {
581                                 os << "\\ensuremath{"
582                                    << c
583                                    << '}';
584                                 column += 13;
585                         } else {
586                                 os << c;
587                         }
588                         break;
589
590                 case '|': case '<': case '>':
591                         // In T1 encoding, these characters exist
592                         if (lyxrc.fontenc == "T1") {
593                                 os << c;
594                                 //... but we should avoid ligatures
595                                 if ((c == '>' || c == '<')
596                                     && i <= size() - 2
597                                     && getChar(i + 1) == c) {
598                                         //os << "\\textcompwordmark{}";
599                                         // Jean-Marc, have a look at
600                                         // this. I think this works
601                                         // equally well:
602                                         os << "\\,{}";
603                                         // Lgb
604                                         column += 19;
605                                 }
606                                 break;
607                         }
608                         // Typewriter font also has them
609                         if (font.family() == LyXFont::TYPEWRITER_FAMILY) {
610                                 os << c;
611                                 break;
612                         }
613                         // Otherwise, we use what LaTeX
614                         // provides us.
615                         switch (c) {
616                         case '<':
617                                 os << "\\textless{}";
618                                 column += 10;
619                                 break;
620                         case '>':
621                                 os << "\\textgreater{}";
622                                 column += 13;
623                                 break;
624                         case '|':
625                                 os << "\\textbar{}";
626                                 column += 9;
627                                 break;
628                         }
629                         break;
630
631                 case '-': // "--" in Typewriter mode -> "-{}-"
632                         if (i <= size() - 2
633                             && getChar(i + 1) == '-'
634                             && font.family() == LyXFont::TYPEWRITER_FAMILY) {
635                                 os << "-{}";
636                                 column += 2;
637                         } else {
638                                 os << '-';
639                         }
640                         break;
641
642                 case '\"':
643                         os << "\\char`\\\"{}";
644                         column += 9;
645                         break;
646
647                 case '£':
648                         if (bparams.inputenc == "default") {
649                                 os << "\\pounds{}";
650                                 column += 8;
651                         } else {
652                                 os << c;
653                         }
654                         break;
655
656                 case '$': case '&':
657                 case '%': case '#': case '{':
658                 case '}': case '_':
659                         os << '\\' << c;
660                         column += 1;
661                         break;
662
663                 case '~':
664                         os << "\\textasciitilde{}";
665                         column += 16;
666                         break;
667
668                 case '^':
669                         os << "\\textasciicircum{}";
670                         column += 17;
671                         break;
672
673                 case '*': case '[': case ']':
674                         // avoid being mistaken for optional arguments
675                         os << '{' << c << '}';
676                         column += 2;
677                         break;
678
679                 case ' ':
680                         // Blanks are printed before font switching.
681                         // Sure? I am not! (try nice-latex)
682                         // I am sure it's correct. LyX might be smarter
683                         // in the future, but for now, nothing wrong is
684                         // written. (Asger)
685                         break;
686
687                 default:
688
689                         // I assume this is hack treating typewriter as verbatim
690                         if (font.family() == LyXFont::TYPEWRITER_FAMILY) {
691                                 if (c != '\0') {
692                                         os << c;
693                                 }
694                                 break;
695                         }
696
697                         // LyX, LaTeX etc.
698
699                         // FIXME: if we have "LaTeX" with a font
700                         // change in the middle (before the 'T', then
701                         // the "TeX" part is still special cased.
702                         // Really we should only operate this on
703                         // "words" for some definition of word
704
705                         size_t pnr = 0;
706
707                         for (; pnr < phrases_nr; ++pnr) {
708                                 if (isTextAt(special_phrases[pnr].phrase, i)) {
709                                         os << special_phrases[pnr].macro;
710                                         i += special_phrases[pnr].phrase.length() - 1;
711                                         column += special_phrases[pnr].macro.length() - 1;
712                                         break;
713                                 }
714                         }
715
716                         if (pnr == phrases_nr && c != '\0') {
717                                 os << c;
718                         }
719                         break;
720                 }
721         }
722 }
723
724
725 void Paragraph::Pimpl::validate(LaTeXFeatures & features,
726                                 LyXLayout const & layout) const
727 {
728         BufferParams const & bparams = features.bufferParams();
729
730         // check the params.
731         if (!params.spacing().isDefault())
732                 features.require("setspace");
733
734         // then the layouts
735         features.useLayout(layout.name());
736
737         // then the fonts
738         Language const * doc_language = bparams.language;
739
740         FontList::const_iterator fcit = fontlist.begin();
741         FontList::const_iterator fend = fontlist.end();
742         for (; fcit != fend; ++fcit) {
743                 if (fcit->font().noun() == LyXFont::ON) {
744                         lyxerr[Debug::LATEX] << "font.noun: "
745                                              << fcit->font().noun()
746                                              << endl;
747                         features.require("noun");
748                         lyxerr[Debug::LATEX] << "Noun enabled. Font: "
749                                              << fcit->font().stateText(0)
750                                              << endl;
751                 }
752                 switch (fcit->font().color()) {
753                 case LColor::none:
754                 case LColor::inherit:
755                 case LColor::ignore:
756                         // probably we should put here all interface colors used for
757                         // font displaying! For now I just add this ones I know of (Jug)
758                 case LColor::latex:
759                 case LColor::note:
760                         break;
761                 default:
762                         features.require("color");
763                         lyxerr[Debug::LATEX] << "Color enabled. Font: "
764                                              << fcit->font().stateText(0)
765                                              << endl;
766                 }
767
768                 Language const * language = fcit->font().language();
769                 if (language->babel() != doc_language->babel() &&
770                     language != ignore_language &&
771                     language != latex_language)
772                 {
773                         features.useLanguage(language);
774                         lyxerr[Debug::LATEX] << "Found language "
775                                              << language->babel() << endl;
776                 }
777         }
778
779         if (!params.leftIndent().zero())
780                 features.require("ParagraphLeftIndent");
781
782         // then the insets
783         InsetList::iterator icit = owner_->insetlist.begin();
784         InsetList::iterator iend = owner_->insetlist.end();
785         for (; icit != iend; ++icit) {
786                 if (icit->inset) {
787                         icit->inset->validate(features);
788                         if (layout.needprotect &&
789                             icit->inset->lyxCode() == InsetBase::FOOT_CODE)
790                                 features.require("NeedLyXFootnoteCode");
791                 }
792         }
793
794         // then the contents
795         for (pos_type i = 0; i < size() ; ++i) {
796                 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
797                         if (!special_phrases[pnr].builtin
798                             && isTextAt(special_phrases[pnr].phrase, i)) {
799                                 features.require(special_phrases[pnr].phrase);
800                                 break;
801                         }
802                 }
803         }
804 }