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