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