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