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