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