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