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