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