]> git.lyx.org Git - lyx.git/blob - src/paragraph_pimpl.C
dba667654409568b21c428f77345c19a7312a36c
[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                 lyxerr << "getChar() on pos " << pos << " in par id "
265                         << owner_->id() << " of size " << siz
266                         << "  is a bit silly !" << endl;
267                 return '\0';
268         }
269
270         return text[pos];
271 }
272
273
274 void Paragraph::Pimpl::setChar(pos_type pos, value_type c)
275 {
276 #warning changes
277         text[pos] = c;
278 }
279
280
281 void Paragraph::Pimpl::insertChar(pos_type pos, value_type c,
282                                   LyXFont const & font, Change change)
283 {
284         lyx::Assert(pos <= size());
285
286         if (tracking()) {
287                 changes_->record(change, pos);
288         }
289
290         // This is actually very common when parsing buffers (and
291         // maybe inserting ascii text)
292         if (pos == size()) {
293                 // when appending characters, no need to update tables
294                 text.push_back(c);
295                 owner_->setFont(pos, font);
296                 return;
297         }
298
299         text.insert(text.begin() + pos, c);
300
301         // Update the font table.
302         FontTable search_font(pos, LyXFont());
303         for (FontList::iterator it = lower_bound(fontlist.begin(),
304                                                       fontlist.end(),
305                                                       search_font, matchFT());
306              it != fontlist.end(); ++it)
307         {
308                 it->pos(it->pos() + 1);
309         }
310
311         // Update the insets
312         owner_->insetlist.increasePosAfterPos(pos);
313
314         owner_->setFont(pos, font);
315 }
316
317
318 void Paragraph::Pimpl::insertInset(pos_type pos,
319                                    Inset * inset, LyXFont const & font, Change change)
320 {
321         lyx::Assert(inset);
322         lyx::Assert(pos <= size());
323
324         insertChar(pos, META_INSET, font, change);
325         lyx::Assert(text[pos] == META_INSET);
326
327         // Add a new entry in the insetlist.
328         owner_->insetlist.insert(inset, pos);
329         inset->parOwner(owner_);
330
331         if (inset_owner)
332                 inset->setOwner(inset_owner);
333 }
334
335
336 bool Paragraph::Pimpl::erasePos(pos_type pos)
337 {
338         lyx::Assert(pos < size());
339
340         if (tracking()) {
341                 Change::Type changetype(changes_->lookup(pos));
342                 changes_->record(Change(Change::DELETED), pos);
343
344                 // only allow the actual removal if it was /new/ text
345                 if (changetype != Change::INSERTED) {
346                         if (text[pos] == Paragraph::META_INSET) {
347                                 Inset * i(owner_->getInset(pos));
348                                 i->markErased();
349                         }
350                         return false;
351                 }
352         }
353
354         eraseIntern(pos);
355         return true;
356 }
357
358
359 void Paragraph::Pimpl::eraseIntern(pos_type pos)
360 {
361         // if it is an inset, delete the inset entry
362         if (text[pos] == Paragraph::META_INSET) {
363                 owner_->insetlist.erase(pos);
364         }
365
366         text.erase(text.begin() + pos);
367
368         // Erase entries in the tables.
369         FontTable search_font(pos, LyXFont());
370
371         FontList::iterator it =
372                 lower_bound(fontlist.begin(),
373                             fontlist.end(),
374                             search_font, matchFT());
375         if (it != fontlist.end() && it->pos() == pos &&
376             (pos == 0 ||
377              (it != fontlist.begin()
378               && boost::prior(it)->pos() == pos - 1))) {
379                 // If it is a multi-character font
380                 // entry, we just make it smaller
381                 // (see update below), otherwise we
382                 // should delete it.
383                 unsigned int const i = it - fontlist.begin();
384                 fontlist.erase(fontlist.begin() + i);
385                 it = fontlist.begin() + i;
386                 if (i > 0 && i < fontlist.size() &&
387                     fontlist[i - 1].font() == fontlist[i].font()) {
388                         fontlist.erase(fontlist.begin() + i - 1);
389                         it = fontlist.begin() + i - 1;
390                 }
391         }
392
393         // Update all other entries.
394         FontList::iterator fend = fontlist.end();
395         for (; it != fend; ++it)
396                 it->pos(it->pos() - 1);
397
398         // Update the insetlist.
399         owner_->insetlist.decreasePosAfterPos(pos);
400 }
401
402
403 void Paragraph::Pimpl::erase(pos_type pos)
404 {
405         erasePos(pos);
406 }
407
408
409 bool Paragraph::Pimpl::erase(pos_type start, pos_type end)
410 {
411         pos_type i = start;
412         pos_type count = end - start;
413         bool any_erased = false;
414
415         while (count) {
416                 if (!erasePos(i)) {
417                         ++i;
418                 } else {
419                         any_erased = true;
420                 }
421                 --count;
422         }
423         return any_erased;
424 }
425
426
427 void Paragraph::Pimpl::simpleTeXBlanks(ostream & os, TexRow & texrow,
428                                        pos_type const i,
429                                        unsigned int & column,
430                                        LyXFont const & font,
431                                        LyXLayout const & style)
432 {
433         if (style.pass_thru) return;
434         if (column > lyxrc.ascii_linelen
435             && i
436             && getChar(i - 1) != ' '
437             && (i < size() - 1)
438             // same in FreeSpacing mode
439             && !style.free_spacing
440                 && !owner_->isFreeSpacing()
441             // In typewriter mode, we want to avoid
442             // ! . ? : at the end of a line
443             && !(font.family() == LyXFont::TYPEWRITER_FAMILY
444                  && (getChar(i - 1) == '.'
445                      || getChar(i - 1) == '?'
446                      || getChar(i - 1) == ':'
447                      || getChar(i - 1) == '!'))) {
448                 os << '\n';
449                 texrow.newline();
450                 texrow.start(owner_, i + 1);
451                 column = 0;
452         } else if (style.free_spacing) {
453                 os << '~';
454         } else {
455                 os << ' ';
456         }
457 }
458
459
460 bool Paragraph::Pimpl::isTextAt(string const & str, pos_type pos) const
461 {
462         pos_type const len = str.length();
463
464         // is the paragraph large enough?
465         if (pos + len > size())
466                 return false;
467
468         // does the wanted text start at point?
469         for (string::size_type i = 0; i < str.length(); ++i) {
470                 if (str[i] != text[pos + i])
471                         return false;
472         }
473
474         // is there a font change in middle of the word?
475         FontList::const_iterator cit = fontlist.begin();
476         FontList::const_iterator end = fontlist.end();
477         for (; cit != end; ++cit) {
478                 if (cit->pos() >= pos)
479                         break;
480         }
481         if (cit != end && pos + len - 1 > cit->pos())
482                 return false;
483
484         return true;
485 }
486
487
488 void Paragraph::Pimpl::simpleTeXSpecialChars(Buffer const * buf,
489                                              BufferParams const & bparams,
490                                              ostream & os,
491                                              TexRow & texrow,
492                                              bool moving_arg,
493                                              LyXFont & font,
494                                              LyXFont & running_font,
495                                              LyXFont & basefont,
496                                              bool & open_font,
497                                              Change::Type & running_change,
498                                              LyXLayout const & style,
499                                              pos_type & i,
500                                              unsigned int & column,
501                                              value_type const c)
502 {
503         if (style.pass_thru) {
504                 if (c != '\0')
505                         os << c;
506                 return;
507         }
508
509         // Two major modes:  LaTeX or plain
510         // Handle here those cases common to both modes
511         // and then split to handle the two modes separately.
512         switch (c) {
513         case Paragraph::META_INSET: {
514                 Inset * inset = owner_->getInset(i);
515
516                 // FIXME: remove this check
517                 if (!inset)
518                         break;
519
520                 if (inset->isTextInset()) {
521                         column += Changes::latexMarkChange(os, running_change,
522                                 Change::UNCHANGED);
523                         running_change = Change::UNCHANGED;
524                 }
525
526                 bool close = false;
527                 int const len = os.tellp();
528                 //ostream::pos_type const len = os.tellp();
529                 if ((inset->lyxCode() == Inset::GRAPHICS_CODE
530                      || inset->lyxCode() == Inset::MATH_CODE
531                      || inset->lyxCode() == Inset::URL_CODE)
532                     && running_font.isRightToLeft()) {
533                         os << "\\L{";
534                         close = true;
535                 }
536
537 #ifdef WITH_WARNINGS
538 #warning Bug: we can have an empty font change here!
539 // if there has just been a font change, we are going to close it
540 // right now, which means stupid latex code like \textsf{}. AFAIK,
541 // this does not harm dvi output. A minor bug, thus (JMarc)
542 #endif
543                 // some insets cannot be inside a font change command
544                 if (open_font && inset->noFontChange()) {
545                         column +=running_font.
546                                 latexWriteEndChanges(os,
547                                                      basefont,
548                                                      basefont);
549                         open_font = false;
550                         basefont = owner_->getLayoutFont(bparams);
551                         running_font = basefont;
552                 }
553
554                 int tmp = inset->latex(buf, os, moving_arg,
555                                        style.free_spacing);
556
557                 if (close)
558                         os << '}';
559
560                 if (tmp) {
561                         for (int j = 0; j < tmp; ++j) {
562                                 texrow.newline();
563                         }
564                         texrow.start(owner_, i + 1);
565                         column = 0;
566                 } else {
567                         column += int(os.tellp()) - len;
568                 }
569         }
570         break;
571
572         case Paragraph::META_NEWLINE:
573                 if (open_font) {
574                         column += running_font.latexWriteEndChanges(os,
575                                                                     basefont,
576                                                                     basefont);
577                         open_font = false;
578                 }
579                 basefont = owner_->getLayoutFont(bparams);
580                 running_font = basefont;
581                 break;
582
583         default:
584                 // And now for the special cases within each mode
585
586                 switch (c) {
587                 case '\\':
588                         os << "\\textbackslash{}";
589                         column += 15;
590                         break;
591
592                 case '±': case '²': case '³':
593                 case '×': case '÷': case '¹':
594                 case '¬': case 'µ':
595                         if ((bparams.inputenc == "latin1" ||
596                              bparams.inputenc == "latin9") ||
597                             (bparams.inputenc == "auto" &&
598                              (font.language()->encoding()->LatexName()
599                               == "latin1" ||
600                               font.language()->encoding()->LatexName()
601                               == "latin9"))) {
602                                 os << "\\ensuremath{"
603                                    << c
604                                    << '}';
605                                 column += 13;
606                         } else {
607                                 os << c;
608                         }
609                         break;
610
611                 case '|': case '<': case '>':
612                         // In T1 encoding, these characters exist
613                         if (lyxrc.fontenc == "T1") {
614                                 os << c;
615                                 //... but we should avoid ligatures
616                                 if ((c == '>' || c == '<')
617                                     && i <= size() - 2
618                                     && getChar(i + 1) == c) {
619                                         //os << "\\textcompwordmark{}";
620                                         // Jean-Marc, have a look at
621                                         // this. I think this works
622                                         // equally well:
623                                         os << "\\,{}";
624                                         // Lgb
625                                         column += 19;
626                                 }
627                                 break;
628                         }
629                         // Typewriter font also has them
630                         if (font.family() == LyXFont::TYPEWRITER_FAMILY) {
631                                 os << c;
632                                 break;
633                         }
634                         // Otherwise, we use what LaTeX
635                         // provides us.
636                         switch (c) {
637                         case '<':
638                                 os << "\\textless{}";
639                                 column += 10;
640                                 break;
641                         case '>':
642                                 os << "\\textgreater{}";
643                                 column += 13;
644                                 break;
645                         case '|':
646                                 os << "\\textbar{}";
647                                 column += 9;
648                                 break;
649                         }
650                         break;
651
652                 case '-': // "--" in Typewriter mode -> "-{}-"
653                         if (i <= size() - 2
654                             && getChar(i + 1) == '-'
655                             && font.family() == LyXFont::TYPEWRITER_FAMILY) {
656                                 os << "-{}";
657                                 column += 2;
658                         } else {
659                                 os << '-';
660                         }
661                         break;
662
663                 case '\"':
664                         os << "\\char`\\\"{}";
665                         column += 9;
666                         break;
667
668                 case '£':
669                         if (bparams.inputenc == "default") {
670                                 os << "\\pounds{}";
671                                 column += 8;
672                         } else {
673                                 os << c;
674                         }
675                         break;
676
677                 case '$': case '&':
678                 case '%': case '#': case '{':
679                 case '}': case '_':
680                         os << '\\' << c;
681                         column += 1;
682                         break;
683
684                 case '~':
685                         os << "\\textasciitilde{}";
686                         column += 16;
687                         break;
688
689                 case '^':
690                         os << "\\textasciicircum{}";
691                         column += 17;
692                         break;
693
694                 case '*': case '[': case ']':
695                         // avoid being mistaken for optional arguments
696                         os << '{' << c << '}';
697                         column += 2;
698                         break;
699
700                 case ' ':
701                         // Blanks are printed before font switching.
702                         // Sure? I am not! (try nice-latex)
703                         // I am sure it's correct. LyX might be smarter
704                         // in the future, but for now, nothing wrong is
705                         // written. (Asger)
706                         break;
707
708                 default:
709
710                         // I assume this is hack treating typewriter as verbatim
711                         if (font.family() == LyXFont::TYPEWRITER_FAMILY) {
712                                 if (c != '\0') {
713                                         os << c;
714                                 }
715                                 break;
716                         }
717
718                         // LyX, LaTeX etc.
719
720                         // FIXME: if we have "LaTeX" with a font
721                         // change in the middle (before the 'T', then
722                         // the "TeX" part is still special cased.
723                         // Really we should only operate this on
724                         // "words" for some definition of word
725
726                         size_t pnr = 0;
727
728                         for (; pnr < phrases_nr; ++pnr) {
729                                 if (isTextAt(special_phrases[pnr].phrase, i)) {
730                                         os << special_phrases[pnr].macro;
731                                         i += special_phrases[pnr].phrase.length() - 1;
732                                         column += special_phrases[pnr].macro.length() - 1;
733                                         break;
734                                 }
735                         }
736
737                         if (pnr == phrases_nr && c != '\0') {
738                                 os << c;
739                         }
740                         break;
741                 }
742         }
743 }
744
745
746 void Paragraph::Pimpl::validate(LaTeXFeatures & features,
747                                 LyXLayout const & layout) const
748 {
749         BufferParams const & bparams = features.bufferParams();
750
751         // check the params.
752         if (params.lineTop() || params.lineBottom())
753                 features.require("lyxline");
754         if (!params.spacing().isDefault())
755                 features.require("setspace");
756
757         // then the layouts
758         features.useLayout(layout.name());
759
760         // then the fonts
761         Language const * doc_language = bparams.language;
762
763         FontList::const_iterator fcit = fontlist.begin();
764         FontList::const_iterator fend = fontlist.end();
765         for (; fcit != fend; ++fcit) {
766                 if (fcit->font().noun() == LyXFont::ON) {
767                         lyxerr[Debug::LATEX] << "font.noun: "
768                                              << fcit->font().noun()
769                                              << endl;
770                         features.require("noun");
771                         lyxerr[Debug::LATEX] << "Noun enabled. Font: "
772                                              << fcit->font().stateText(0)
773                                              << endl;
774                 }
775                 switch (fcit->font().color()) {
776                 case LColor::none:
777                 case LColor::inherit:
778                 case LColor::ignore:
779                         // probably we should put here all interface colors used for
780                         // font displaying! For now I just add this ones I know of (Jug)
781                 case LColor::latex:
782                 case LColor::note:
783                         break;
784                 default:
785                         features.require("color");
786                         lyxerr[Debug::LATEX] << "Color enabled. Font: "
787                                              << fcit->font().stateText(0)
788                                              << endl;
789                 }
790
791                 Language const * language = fcit->font().language();
792                 if (language->babel() != doc_language->babel() &&
793                     language != ignore_language &&
794                     language != latex_language)
795                 {
796                         features.useLanguage(language);
797                         lyxerr[Debug::LATEX] << "Found language "
798                                              << language->babel() << endl;
799                 }
800         }
801
802         if (!params.leftIndent().zero())
803                 features.require("ParagraphLeftIndent");
804
805         // then the insets
806         InsetList::iterator icit = owner_->insetlist.begin();
807         InsetList::iterator iend = owner_->insetlist.end();
808         for (; icit != iend; ++icit) {
809                 if (icit.getInset()) {
810                         icit.getInset()->validate(features);
811                         if (layout.needprotect &&
812                             icit.getInset()->lyxCode() == Inset::FOOT_CODE)
813                                 features.require("NeedLyXFootnoteCode");
814                 }
815         }
816
817         // then the contents
818         for (pos_type i = 0; i < size() ; ++i) {
819                 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
820                         if (!special_phrases[pnr].builtin
821                             && isTextAt(special_phrases[pnr].phrase, i)) {
822                                 features.require(special_phrases[pnr].phrase);
823                                 break;
824                         }
825                 }
826         }
827 }
828
829
830 LyXFont const Paragraph::Pimpl::realizeFont(LyXFont const & font,
831                                             BufferParams const & bparams) const
832 {
833         LyXFont tmpfont(font);
834
835         // check for environment font information
836         char par_depth = owner_->getDepth();
837         Paragraph const * par = owner_;
838         LyXTextClass const & tclass = bparams.getLyXTextClass();
839
840         while (par && par->getDepth() && !tmpfont.resolved()) {
841                 par = par->outerHook();
842                 if (par) {
843                         tmpfont.realize(par->layout()->font);
844                         par_depth = par->getDepth();
845                 }
846         }
847
848         tmpfont.realize(tclass.defaultfont());
849         return tmpfont;
850 }