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