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