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