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