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