]> git.lyx.org Git - lyx.git/blob - src/paragraph_pimpl.C
move some functions around
[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') os << c;
501                 return;
502         }
503         // Two major modes:  LaTeX or plain
504         // Handle here those cases common to both modes
505         // and then split to handle the two modes separately.
506         switch (c) {
507         case Paragraph::META_INSET: {
508                 Inset * inset = owner_->getInset(i);
509
510                 // FIXME: remove this check
511                 if (!inset)
512                         break;
513
514                 if (inset->isTextInset()) {
515                         column += Changes::latexMarkChange(os, running_change,
516                                 Change::UNCHANGED);
517                         running_change = Change::UNCHANGED;
518                 }
519
520                 bool close = false;
521                 int const len = os.tellp();
522                 //ostream::pos_type const len = os.tellp();
523                 if ((inset->lyxCode() == Inset::GRAPHICS_CODE
524                      || inset->lyxCode() == Inset::MATH_CODE
525                      || inset->lyxCode() == Inset::URL_CODE)
526                     && running_font.isRightToLeft()) {
527                         os << "\\L{";
528                         close = true;
529                 }
530
531 #ifdef WITH_WARNINGS
532 #warning Bug: we can have an empty font change here!
533 // if there has just been a font change, we are going to close it
534 // right now, which means stupid latex code like \textsf{}. AFAIK,
535 // this does not harm dvi output. A minor bug, thus (JMarc)
536 #endif
537                 // some insets cannot be inside a font change command
538                 if (open_font && inset->noFontChange()) {
539                         column +=running_font.
540                                 latexWriteEndChanges(os,
541                                                      basefont,
542                                                      basefont);
543                         open_font = false;
544                         basefont = owner_->getLayoutFont(bparams);
545                         running_font = basefont;
546                 }
547
548                 int tmp = inset->latex(buf, os, moving_arg,
549                                        style.free_spacing);
550
551                 if (close)
552                         os << '}';
553
554                 if (tmp) {
555                         for (int j = 0; j < tmp; ++j) {
556                                 texrow.newline();
557                         }
558                         texrow.start(owner_, i + 1);
559                         column = 0;
560                 } else {
561                         column += int(os.tellp()) - len;
562                 }
563         }
564         break;
565
566         case Paragraph::META_NEWLINE:
567                 if (open_font) {
568                         column += running_font.latexWriteEndChanges(os,
569                                                                     basefont,
570                                                                     basefont);
571                         open_font = false;
572                 }
573                 basefont = owner_->getLayoutFont(bparams);
574                 running_font = basefont;
575                 break;
576
577         case Paragraph::META_HFILL:
578                 os << "\\hfill{}";
579                 column += 7;
580                 break;
581
582         default:
583                 // And now for the special cases within each mode
584
585                 switch (c) {
586                 case '\\':
587                         os << "\\textbackslash{}";
588                         column += 15;
589                         break;
590
591                 case '±': case '²': case '³':
592                 case '×': case '÷': case '¹':
593                 case '¬': case 'µ':
594                         if ((bparams.inputenc == "latin1" ||
595                              bparams.inputenc == "latin9") ||
596                             (bparams.inputenc == "auto" &&
597                              (font.language()->encoding()->LatexName()
598                               == "latin1" ||
599                               font.language()->encoding()->LatexName()
600                               == "latin9"))) {
601                                 os << "\\ensuremath{"
602                                    << c
603                                    << '}';
604                                 column += 13;
605                         } else {
606                                 os << c;
607                         }
608                         break;
609
610                 case '|': case '<': case '>':
611                         // In T1 encoding, these characters exist
612                         if (lyxrc.fontenc == "T1") {
613                                 os << c;
614                                 //... but we should avoid ligatures
615                                 if ((c == '>' || c == '<')
616                                     && i <= size() - 2
617                                     && getChar(i + 1) == c) {
618                                         //os << "\\textcompwordmark{}";
619                                         // Jean-Marc, have a look at
620                                         // this. I think this works
621                                         // equally well:
622                                         os << "\\,{}";
623                                         // Lgb
624                                         column += 19;
625                                 }
626                                 break;
627                         }
628                         // Typewriter font also has them
629                         if (font.family() == LyXFont::TYPEWRITER_FAMILY) {
630                                 os << c;
631                                 break;
632                         }
633                         // Otherwise, we use what LaTeX
634                         // provides us.
635                         switch (c) {
636                         case '<':
637                                 os << "\\textless{}";
638                                 column += 10;
639                                 break;
640                         case '>':
641                                 os << "\\textgreater{}";
642                                 column += 13;
643                                 break;
644                         case '|':
645                                 os << "\\textbar{}";
646                                 column += 9;
647                                 break;
648                         }
649                         break;
650
651                 case '-': // "--" in Typewriter mode -> "-{}-"
652                         if (i <= size() - 2
653                             && getChar(i + 1) == '-'
654                             && font.family() == LyXFont::TYPEWRITER_FAMILY) {
655                                 os << "-{}";
656                                 column += 2;
657                         } else {
658                                 os << '-';
659                         }
660                         break;
661
662                 case '\"':
663                         os << "\\char`\\\"{}";
664                         column += 9;
665                         break;
666
667                 case '£':
668                         if (bparams.inputenc == "default") {
669                                 os << "\\pounds{}";
670                                 column += 8;
671                         } else {
672                                 os << c;
673                         }
674                         break;
675
676                 case '$': case '&':
677                 case '%': case '#': case '{':
678                 case '}': case '_':
679                         os << '\\' << c;
680                         column += 1;
681                         break;
682
683                 case '~':
684                         os << "\\textasciitilde{}";
685                         column += 16;
686                         break;
687
688                 case '^':
689                         os << "\\textasciicircum{}";
690                         column += 17;
691                         break;
692
693                 case '*': case '[': case ']':
694                         // avoid being mistaken for optional arguments
695                         os << '{' << c << '}';
696                         column += 2;
697                         break;
698
699                 case ' ':
700                         // Blanks are printed before font switching.
701                         // Sure? I am not! (try nice-latex)
702                         // I am sure it's correct. LyX might be smarter
703                         // in the future, but for now, nothing wrong is
704                         // written. (Asger)
705                         break;
706
707                 default:
708
709                         // I assume this is hack treating typewriter as verbatim
710                         if (font.family() == LyXFont::TYPEWRITER_FAMILY) {
711                                 if (c != '\0') {
712                                         os << c;
713                                 }
714                                 break;
715                         }
716
717                         // LyX, LaTeX etc.
718
719                         // FIXME: if we have "LaTeX" with a font
720                         // change in the middle (before the 'T', then
721                         // the "TeX" part is still special cased.
722                         // Really we should only operate this on
723                         // "words" for some definition of word
724
725                         size_t pnr = 0;
726
727                         for (; pnr < phrases_nr; ++pnr) {
728                                 if (isTextAt(special_phrases[pnr].phrase, i)) {
729                                         os << special_phrases[pnr].macro;
730                                         i += special_phrases[pnr].phrase.length() - 1;
731                                         column += special_phrases[pnr].macro.length() - 1;
732                                         break;
733                                 }
734                         }
735
736                         if (pnr == phrases_nr && c != '\0') {
737                                 os << c;
738                         }
739                         break;
740                 }
741         }
742 }
743
744
745 void Paragraph::Pimpl::validate(LaTeXFeatures & features,
746                                 LyXLayout const & layout) const
747 {
748         BufferParams const & bparams = features.bufferParams();
749
750         // check the params.
751         if (params.lineTop() || params.lineBottom())
752                 features.require("lyxline");
753         if (!params.spacing().isDefault())
754                 features.require("setspace");
755
756         // then the layouts
757         features.useLayout(layout.name());
758
759         // then the fonts
760         Language const * doc_language = bparams.language;
761
762         FontList::const_iterator fcit = fontlist.begin();
763         FontList::const_iterator fend = fontlist.end();
764         for (; fcit != fend; ++fcit) {
765                 if (fcit->font().noun() == LyXFont::ON) {
766                         lyxerr[Debug::LATEX] << "font.noun: "
767                                              << fcit->font().noun()
768                                              << endl;
769                         features.require("noun");
770                         lyxerr[Debug::LATEX] << "Noun enabled. Font: "
771                                              << fcit->font().stateText(0)
772                                              << endl;
773                 }
774                 switch (fcit->font().color()) {
775                 case LColor::none:
776                 case LColor::inherit:
777                 case LColor::ignore:
778                         // probably we should put here all interface colors used for
779                         // font displaying! For now I just add this ones I know of (Jug)
780                 case LColor::latex:
781                 case LColor::note:
782                         break;
783                 default:
784                         features.require("color");
785                         lyxerr[Debug::LATEX] << "Color enabled. Font: "
786                                              << fcit->font().stateText(0)
787                                              << endl;
788                 }
789
790                 Language const * language = fcit->font().language();
791                 if (language->babel() != doc_language->babel() &&
792                     language != ignore_language &&
793                     language != latex_language)
794                 {
795                         features.useLanguage(language);
796                         lyxerr[Debug::LATEX] << "Found language "
797                                              << language->babel() << endl;
798                 }
799         }
800
801         if (!params.leftIndent().zero())
802                 features.require("ParagraphLeftIndent");
803
804         // then the insets
805         InsetList::iterator icit = owner_->insetlist.begin();
806         InsetList::iterator iend = owner_->insetlist.end();
807         for (; icit != iend; ++icit) {
808                 if (icit.getInset()) {
809                         icit.getInset()->validate(features);
810                         if (layout.needprotect &&
811                             icit.getInset()->lyxCode() == Inset::FOOT_CODE)
812                                 features.require("NeedLyXFootnoteCode");
813                 }
814         }
815
816         // then the contents
817         for (pos_type i = 0; i < size() ; ++i) {
818                 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
819                         if (!special_phrases[pnr].builtin
820                             && isTextAt(special_phrases[pnr].phrase, i)) {
821                                 features.require(special_phrases[pnr].phrase);
822                                 break;
823                         }
824                 }
825         }
826 }
827
828
829 LyXFont const Paragraph::Pimpl::realizeFont(LyXFont const & font,
830                                             BufferParams const & bparams) const
831 {
832         LyXFont tmpfont(font);
833
834         // check for environment font information
835         char par_depth = owner_->getDepth();
836         Paragraph const * par = owner_;
837         LyXTextClass const & tclass = bparams.getLyXTextClass();
838
839         while (par && par->getDepth() && !tmpfont.resolved()) {
840                 par = par->outerHook();
841                 if (par) {
842                         tmpfont.realize(par->layout()->font);
843                         par_depth = par->getDepth();
844                 }
845         }
846
847         tmpfont.realize(tclass.defaultfont());
848         return tmpfont;
849 }