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