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