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