]> git.lyx.org Git - lyx.git/blob - src/text.C
* src/text.C: remove change tracking FIXME
[lyx.git] / src / text.C
1 /**
2  * \file src/text.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Asger Alstrup
7  * \author Lars Gullik Bjønnes
8  * \author Jean-Marc Lasgouttes
9  * \author John Levon
10  * \author André Pönitz
11  * \author Dekel Tsur
12  * \author Jürgen Vigna
13  *
14  * Full author contact details are available in file CREDITS.
15  */
16
17 #include <config.h>
18
19 #include "lyxtext.h"
20
21 #include "author.h"
22 #include "buffer.h"
23 #include "buffer_funcs.h"
24 #include "bufferparams.h"
25 #include "BufferView.h"
26 #include "cursor.h"
27 #include "pariterator.h"
28 #include "coordcache.h"
29 #include "CutAndPaste.h"
30 #include "debug.h"
31 #include "dispatchresult.h"
32 #include "encoding.h"
33 #include "errorlist.h"
34 #include "funcrequest.h"
35 #include "factory.h"
36 #include "FontIterator.h"
37 #include "gettext.h"
38 #include "language.h"
39 #include "LColor.h"
40 #include "lyxlength.h"
41 #include "lyxlex.h"
42 #include "lyxrc.h"
43 #include "lyxrow.h"
44 #include "metricsinfo.h"
45 #include "paragraph.h"
46 #include "paragraph_funcs.h"
47 #include "ParagraphParameters.h"
48 #include "rowpainter.h"
49 #include "undo.h"
50 #include "vspace.h"
51 #include "WordLangTuple.h"
52
53 #include "frontends/FontMetrics.h"
54 #include "frontends/Painter.h"
55
56 #include "insets/insettext.h"
57 #include "insets/insetbibitem.h"
58 #include "insets/insethfill.h"
59 #include "insets/insetlatexaccent.h"
60 #include "insets/insetline.h"
61 #include "insets/insetnewline.h"
62 #include "insets/insetpagebreak.h"
63 #include "insets/insetoptarg.h"
64 #include "insets/insetspace.h"
65 #include "insets/insetspecialchar.h"
66 #include "insets/insettabular.h"
67
68 #include "support/lstrings.h"
69 #include "support/textutils.h"
70 #include "support/convert.h"
71
72 #include <boost/current_function.hpp>
73
74 #include <sstream>
75
76
77 namespace lyx {
78
79 using support::bformat;
80 using support::contains;
81 using support::lowercase;
82 using support::split;
83 using support::uppercase;
84
85 using cap::cutSelection;
86 using cap::pasteParagraphList;
87
88 using frontend::FontMetrics;
89
90 using std::auto_ptr;
91 using std::advance;
92 using std::distance;
93 using std::max;
94 using std::min;
95 using std::endl;
96 using std::string;
97
98
99 namespace {
100
101 int numberOfSeparators(Paragraph const & par, Row const & row)
102 {
103         pos_type const first = max(row.pos(), par.beginOfBody());
104         pos_type const last = row.endpos() - 1;
105         int n = 0;
106         for (pos_type p = first; p < last; ++p) {
107                 if (par.isSeparator(p))
108                         ++n;
109         }
110         return n;
111 }
112
113
114 int numberOfLabelHfills(Paragraph const & par, Row const & row)
115 {
116         pos_type last = row.endpos() - 1;
117         pos_type first = row.pos();
118
119         // hfill *DO* count at the beginning of paragraphs!
120         if (first) {
121                 while (first < last && par.isHfill(first))
122                         ++first;
123         }
124
125         last = min(last, par.beginOfBody());
126         int n = 0;
127         for (pos_type p = first; p < last; ++p) {
128                 if (par.isHfill(p))
129                         ++n;
130         }
131         return n;
132 }
133
134
135 int numberOfHfills(Paragraph const & par, Row const & row)
136 {
137         pos_type const last = row.endpos();
138         pos_type first = row.pos();
139
140         // hfill *DO* count at the beginning of paragraphs!
141         if (first) {
142                 while (first < last && par.isHfill(first))
143                         ++first;
144         }
145
146         first = max(first, par.beginOfBody());
147
148         int n = 0;
149         for (pos_type p = first; p < last; ++p) {
150                 if (par.isHfill(p))
151                         ++n;
152         }
153         return n;
154 }
155
156
157 void readParToken(Buffer const & buf, Paragraph & par, LyXLex & lex,
158         string const & token, LyXFont & font, Change & change, ErrorList & errorList)
159 {
160         BufferParams const & bp = buf.params();
161
162         if (token[0] != '\\') {
163 #if 0
164                 string::const_iterator cit = token.begin();
165                 for (; cit != token.end(); ++cit)
166                         par.insertChar(par.size(), (*cit), font, change);
167 #else
168                 docstring dstr = lex.getDocString();
169                 docstring::const_iterator cit = dstr.begin();
170                 docstring::const_iterator cend = dstr.end();
171                 for (; cit != cend; ++cit)
172                         par.insertChar(par.size(), *cit, font, change);
173 #endif
174         } else if (token == "\\begin_layout") {
175                 lex.eatLine();
176                 string layoutname = lex.getString();
177
178                 font = LyXFont(LyXFont::ALL_INHERIT, bp.language);
179                 change = Change(Change::UNCHANGED);
180
181                 LyXTextClass const & tclass = bp.getLyXTextClass();
182
183                 if (layoutname.empty()) {
184                         layoutname = tclass.defaultLayoutName();
185                 }
186
187                 bool hasLayout = tclass.hasLayout(layoutname);
188
189                 if (!hasLayout) {
190                         errorList.push_back(ErrorItem(_("Unknown layout"),
191                         bformat(_("Layout '%1$s' does not exist in textclass '%2$s'\nTrying to use the default instead.\n"),
192                         from_utf8(layoutname), from_utf8(tclass.name())), par.id(), 0, par.size()));
193                         layoutname = tclass.defaultLayoutName();
194                 }
195
196                 par.layout(bp.getLyXTextClass()[layoutname]);
197
198                 // Test whether the layout is obsolete.
199                 LyXLayout_ptr const & layout = par.layout();
200                 if (!layout->obsoleted_by().empty())
201                         par.layout(bp.getLyXTextClass()[layout->obsoleted_by()]);
202
203                 par.params().read(lex);
204
205         } else if (token == "\\end_layout") {
206                 lyxerr << BOOST_CURRENT_FUNCTION
207                        << ": Solitary \\end_layout in line "
208                        << lex.getLineNo() << "\n"
209                        << "Missing \\begin_layout?.\n";
210         } else if (token == "\\end_inset") {
211                 lyxerr << BOOST_CURRENT_FUNCTION
212                        << ": Solitary \\end_inset in line "
213                        << lex.getLineNo() << "\n"
214                        << "Missing \\begin_inset?.\n";
215         } else if (token == "\\begin_inset") {
216                 InsetBase * inset = readInset(lex, buf);
217                 if (inset)
218                         par.insertInset(par.size(), inset, font, change);
219                 else {
220                         lex.eatLine();
221                         docstring line = lex.getDocString();
222                         errorList.push_back(ErrorItem(_("Unknown Inset"), line,
223                                             par.id(), 0, par.size()));
224                 }
225         } else if (token == "\\family") {
226                 lex.next();
227                 font.setLyXFamily(lex.getString());
228         } else if (token == "\\series") {
229                 lex.next();
230                 font.setLyXSeries(lex.getString());
231         } else if (token == "\\shape") {
232                 lex.next();
233                 font.setLyXShape(lex.getString());
234         } else if (token == "\\size") {
235                 lex.next();
236                 font.setLyXSize(lex.getString());
237         } else if (token == "\\lang") {
238                 lex.next();
239                 string const tok = lex.getString();
240                 Language const * lang = languages.getLanguage(tok);
241                 if (lang) {
242                         font.setLanguage(lang);
243                 } else {
244                         font.setLanguage(bp.language);
245                         lex.printError("Unknown language `$$Token'");
246                 }
247         } else if (token == "\\numeric") {
248                 lex.next();
249                 font.setNumber(font.setLyXMisc(lex.getString()));
250         } else if (token == "\\emph") {
251                 lex.next();
252                 font.setEmph(font.setLyXMisc(lex.getString()));
253         } else if (token == "\\bar") {
254                 lex.next();
255                 string const tok = lex.getString();
256
257                 if (tok == "under")
258                         font.setUnderbar(LyXFont::ON);
259                 else if (tok == "no")
260                         font.setUnderbar(LyXFont::OFF);
261                 else if (tok == "default")
262                         font.setUnderbar(LyXFont::INHERIT);
263                 else
264                         lex.printError("Unknown bar font flag "
265                                        "`$$Token'");
266         } else if (token == "\\noun") {
267                 lex.next();
268                 font.setNoun(font.setLyXMisc(lex.getString()));
269         } else if (token == "\\color") {
270                 lex.next();
271                 font.setLyXColor(lex.getString());
272         } else if (token == "\\InsetSpace" || token == "\\SpecialChar") {
273
274                 // Insets don't make sense in a free-spacing context! ---Kayvan
275                 if (par.isFreeSpacing()) {
276                         if (token == "\\InsetSpace")
277                                 par.insertChar(par.size(), ' ', font, change);
278                         else if (lex.isOK()) {
279                                 lex.next();
280                                 string const next_token = lex.getString();
281                                 if (next_token == "\\-")
282                                         par.insertChar(par.size(), '-', font, change);
283                                 else {
284                                         lex.printError("Token `$$Token' "
285                                                        "is in free space "
286                                                        "paragraph layout!");
287                                 }
288                         }
289                 } else {
290                         auto_ptr<InsetBase> inset;
291                         if (token == "\\SpecialChar" )
292                                 inset.reset(new InsetSpecialChar);
293                         else
294                                 inset.reset(new InsetSpace);
295                         inset->read(buf, lex);
296                         par.insertInset(par.size(), inset.release(),
297                                         font, change);
298                 }
299         } else if (token == "\\i") {
300                 auto_ptr<InsetBase> inset(new InsetLatexAccent);
301                 inset->read(buf, lex);
302                 par.insertInset(par.size(), inset.release(), font, change);
303         } else if (token == "\\backslash") {
304                 par.insertChar(par.size(), '\\', font, change);
305         } else if (token == "\\newline") {
306                 auto_ptr<InsetBase> inset(new InsetNewline);
307                 inset->read(buf, lex);
308                 par.insertInset(par.size(), inset.release(), font, change);
309         } else if (token == "\\LyXTable") {
310                 auto_ptr<InsetBase> inset(new InsetTabular(buf));
311                 inset->read(buf, lex);
312                 par.insertInset(par.size(), inset.release(), font, change);
313         } else if (token == "\\hfill") {
314                 par.insertInset(par.size(), new InsetHFill, font, change);
315         } else if (token == "\\lyxline") {
316                 par.insertInset(par.size(), new InsetLine, font, change);
317         } else if (token == "\\newpage") {
318                 par.insertInset(par.size(), new InsetPagebreak, font, change);
319         } else if (token == "\\change_unchanged") {
320                 change = Change(Change::UNCHANGED);
321         } else if (token == "\\change_inserted") {
322                 lex.eatLine();
323                 std::istringstream is(lex.getString());
324                 unsigned int aid;
325                 time_type ct;
326                 is >> aid >> ct;
327                 if (aid >= bp.author_map.size()) {
328                         errorList.push_back(ErrorItem(_("Change tracking error"),
329                                             bformat(_("Unknown author index for insertion: %1$d\n"), aid),
330                                             par.id(), 0, par.size()));
331                         change = Change(Change::UNCHANGED);
332                 } else
333                         change = Change(Change::INSERTED, bp.author_map[aid], ct);
334         } else if (token == "\\change_deleted") {
335                 lex.eatLine();
336                 std::istringstream is(lex.getString());
337                 unsigned int aid;
338                 time_type ct;
339                 is >> aid >> ct;
340                 if (aid >= bp.author_map.size()) {
341                         errorList.push_back(ErrorItem(_("Change tracking error"),
342                                             bformat(_("Unknown author index for deletion: %1$d\n"), aid),
343                                             par.id(), 0, par.size()));
344                         change = Change(Change::UNCHANGED);
345                 } else
346                         change = Change(Change::DELETED, bp.author_map[aid], ct);
347         } else {
348                 lex.eatLine();
349                 errorList.push_back(ErrorItem(_("Unknown token"),
350                         bformat(_("Unknown token: %1$s %2$s\n"), from_utf8(token),
351                         lex.getDocString()),
352                         par.id(), 0, par.size()));
353         }
354 }
355
356
357 void readParagraph(Buffer const & buf, Paragraph & par, LyXLex & lex,
358         ErrorList & errorList)
359 {
360         lex.nextToken();
361         string token = lex.getString();
362         LyXFont font;
363         Change change(Change::UNCHANGED);
364
365         while (lex.isOK()) {
366                 readParToken(buf, par, lex, token, font, change, errorList);
367
368                 lex.nextToken();
369                 token = lex.getString();
370
371                 if (token.empty())
372                         continue;
373
374                 if (token == "\\end_layout") {
375                         //Ok, paragraph finished
376                         break;
377                 }
378
379                 lyxerr[Debug::PARSER] << "Handling paragraph token: `"
380                                       << token << '\'' << endl;
381                 if (token == "\\begin_layout" || token == "\\end_document"
382                     || token == "\\end_inset" || token == "\\begin_deeper"
383                     || token == "\\end_deeper") {
384                         lex.pushToken(token);
385                         lyxerr << "Paragraph ended in line "
386                                << lex.getLineNo() << "\n"
387                                << "Missing \\end_layout.\n";
388                         break;
389                 }
390         }
391         // Final change goes to paragraph break:
392         par.setChange(par.size(), change);
393
394         // Initialize begin_of_body_ on load; redoParagraph maintains
395         par.setBeginOfBody();
396 }
397
398
399 } // namespace anon
400
401
402
403 double LyXText::spacing(Buffer const & buffer,
404                 Paragraph const & par) const
405 {
406         if (par.params().spacing().isDefault())
407                 return buffer.params().spacing().getValue();
408         return par.params().spacing().getValue();
409 }
410
411
412 int LyXText::width() const
413 {
414         return dim_.wid;
415 }
416
417
418 int LyXText::height() const
419 {
420         return dim_.height();
421 }
422
423
424 int LyXText::singleWidth(Buffer const & buffer, Paragraph const & par,
425                 pos_type pos) const
426 {
427         return singleWidth(par, pos, par.getChar(pos),
428                 getFont(buffer, par, pos));
429 }
430
431
432 int LyXText::singleWidth(Paragraph const & par,
433                          pos_type pos, char_type c, LyXFont const & font) const
434 {
435         // The most common case is handled first (Asger)
436         if (isPrintable(c)) {
437                 Language const * language = font.language();
438                 if (language->rightToLeft()) {
439                         if ((lyxrc.font_norm_type == LyXRC::ISO_8859_6_8 ||
440                              lyxrc.font_norm_type == LyXRC::ISO_10646_1)
441                             && language->lang() == "arabic") {
442                                 if (Encodings::isComposeChar_arabic(c))
443                                         return 0;
444                                 c = par.transformChar(c, pos);
445                         } else if (language->lang() == "hebrew" &&
446                                    Encodings::isComposeChar_hebrew(c))
447                                 return 0;
448                 }
449                 return theFontMetrics(font).width(c);
450         }
451
452         if (c == Paragraph::META_INSET)
453                 return par.getInset(pos)->width();
454
455         return theFontMetrics(font).width(c);
456 }
457
458
459 int LyXText::leftMargin(Buffer const & buffer, pit_type pit) const
460 {
461         BOOST_ASSERT(pit >= 0);
462         BOOST_ASSERT(pit < int(pars_.size()));
463         return leftMargin(buffer, pit, pars_[pit].size());
464 }
465
466
467 int LyXText::leftMargin(Buffer const & buffer,
468                 pit_type const pit, pos_type const pos) const
469 {
470         BOOST_ASSERT(pit >= 0);
471         BOOST_ASSERT(pit < int(pars_.size()));
472         Paragraph const & par = pars_[pit];
473         BOOST_ASSERT(pos >= 0);
474         BOOST_ASSERT(pos <= par.size());
475         //lyxerr << "LyXText::leftMargin: pit: " << pit << " pos: " << pos << endl;
476         LyXTextClass const & tclass = buffer.params().getLyXTextClass();
477         LyXLayout_ptr const & layout = par.layout();
478
479         string parindent = layout->parindent;
480
481         int l_margin = 0;
482
483         if (isMainText(buffer))
484                 l_margin += changebarMargin();
485
486         // FIXME UNICODE
487         docstring leftm = from_utf8(tclass.leftmargin());
488         l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(leftm);
489
490         if (par.getDepth() != 0) {
491                 // find the next level paragraph
492                 pit_type newpar = outerHook(pit, pars_);
493                 if (newpar != pit_type(pars_.size())) {
494                         if (pars_[newpar].layout()->isEnvironment()) {
495                                 l_margin = leftMargin(buffer, newpar);
496                         }
497                         if (par.layout() == tclass.defaultLayout()) {
498                                 if (pars_[newpar].params().noindent())
499                                         parindent.erase();
500                                 else
501                                         parindent = pars_[newpar].layout()->parindent;
502                         }
503                 }
504         }
505
506         // This happens after sections in standard classes. The 1.3.x
507         // code compared depths too, but it does not seem necessary
508         // (JMarc)
509         if (par.layout() == tclass.defaultLayout()
510             && pit > 0 && pars_[pit - 1].layout()->nextnoindent)
511                 parindent.erase();
512
513         LyXFont const labelfont = getLabelFont(buffer, par);
514         FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
515
516         switch (layout->margintype) {
517         case MARGIN_DYNAMIC:
518                 if (!layout->leftmargin.empty()) {
519                         // FIXME UNICODE
520                         docstring leftm = from_utf8(layout->leftmargin);
521                         l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(leftm);
522                 }
523                 if (!par.getLabelstring().empty()) {
524                         // FIXME UNICODE
525                         docstring labin = from_utf8(layout->labelindent);
526                         l_margin += labelfont_metrics.signedWidth(labin);
527                         docstring labstr = par.getLabelstring();
528                         l_margin += labelfont_metrics.width(labstr);
529                         docstring labsep = from_utf8(layout->labelsep);
530                         l_margin += labelfont_metrics.width(labsep);
531                 }
532                 break;
533
534         case MARGIN_MANUAL: {
535                 // FIXME UNICODE
536                 docstring labin = from_utf8(layout->labelindent);
537                 l_margin += labelfont_metrics.signedWidth(labin);
538                 // The width of an empty par, even with manual label, should be 0
539                 if (!par.empty() && pos >= par.beginOfBody()) {
540                         if (!par.getLabelWidthString().empty()) {
541                                 docstring labstr = par.getLabelWidthString();
542                                 l_margin += labelfont_metrics.width(labstr);
543                                 docstring labsep = from_utf8(layout->labelsep);
544                                 l_margin += labelfont_metrics.width(labsep);
545                         }
546                 }
547                 break;
548         }
549
550         case MARGIN_STATIC: {
551                 // FIXME UNICODE
552                 docstring leftm = from_utf8(layout->leftmargin);
553                 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(leftm)
554                         * 4     / (par.getDepth() + 4);
555                 break;
556         }
557
558         case MARGIN_FIRST_DYNAMIC:
559                 if (layout->labeltype == LABEL_MANUAL) {
560                         if (pos >= par.beginOfBody()) {
561                                 // FIXME UNICODE
562                                 l_margin += labelfont_metrics.signedWidth(
563                                         from_utf8(layout->leftmargin));
564                         } else {
565                                 // FIXME UNICODE
566                                 l_margin += labelfont_metrics.signedWidth(
567                                         from_utf8(layout->labelindent));
568                         }
569                 } else if (pos != 0
570                            // Special case to fix problems with
571                            // theorems (JMarc)
572                            || (layout->labeltype == LABEL_STATIC
573                                && layout->latextype == LATEX_ENVIRONMENT
574                                && !isFirstInSequence(pit, pars_))) {
575                         // FIXME UNICODE
576                         l_margin += labelfont_metrics.signedWidth(from_utf8(layout->leftmargin));
577                 } else if (layout->labeltype != LABEL_TOP_ENVIRONMENT
578                            && layout->labeltype != LABEL_BIBLIO
579                            && layout->labeltype !=
580                            LABEL_CENTERED_TOP_ENVIRONMENT) {
581                         l_margin += labelfont_metrics.signedWidth(from_utf8(layout->labelindent));
582                         l_margin += labelfont_metrics.width(from_utf8(layout->labelsep));
583                         l_margin += labelfont_metrics.width(par.getLabelstring());
584                 }
585                 break;
586
587         case MARGIN_RIGHT_ADDRESS_BOX: {
588 #if 0
589                 // ok, a terrible hack. The left margin depends on the widest
590                 // row in this paragraph.
591                 RowList::iterator rit = par.rows().begin();
592                 RowList::iterator end = par.rows().end();
593 #ifdef WITH_WARNINGS
594 #warning This is wrong.
595 #endif
596                 int minfill = maxwidth_;
597                 for ( ; rit != end; ++rit)
598                         if (rit->fill() < minfill)
599                                 minfill = rit->fill();
600                 l_margin += theFontMetrics(params.getFont()).signedWidth(layout->leftmargin);
601                 l_margin += minfill;
602 #endif
603                 // also wrong, but much shorter.
604                 l_margin += maxwidth_ / 2;
605                 break;
606         }
607         }
608
609         if (!par.params().leftIndent().zero())
610                 l_margin += par.params().leftIndent().inPixels(maxwidth_);
611
612         LyXAlignment align;
613
614         if (par.params().align() == LYX_ALIGN_LAYOUT)
615                 align = layout->align;
616         else
617                 align = par.params().align();
618
619         // set the correct parindent
620         if (pos == 0
621             && (layout->labeltype == LABEL_NO_LABEL
622                || layout->labeltype == LABEL_TOP_ENVIRONMENT
623                || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
624                || (layout->labeltype == LABEL_STATIC
625                    && layout->latextype == LATEX_ENVIRONMENT
626                    && !isFirstInSequence(pit, pars_)))
627             && align == LYX_ALIGN_BLOCK
628             && !par.params().noindent()
629             // in some insets, paragraphs are never indented
630             && !(par.inInset() && par.inInset()->neverIndent(buffer))
631             // display style insets are always centered, omit indentation
632             && !(!par.empty()
633                     && par.isInset(pos)
634                     && par.getInset(pos)->display())
635             && (par.layout() != tclass.defaultLayout()
636                 || buffer.params().paragraph_separation ==
637                    BufferParams::PARSEP_INDENT))
638         {
639                 docstring din = from_utf8(parindent);
640                 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(din);
641         }
642
643         return l_margin;
644 }
645
646
647 int LyXText::rightMargin(Buffer const & buffer, Paragraph const & par) const
648 {
649         // FIXME: the correct way is to only call rightMargin() only
650         // within the main LyXText. The following test is thus bogus.
651         LyXText const & text = buffer.text();
652         // We do not want rightmargins on inner texts.
653         if (&text != this)
654                 return 0;
655
656         BufferParams const & params = buffer.params();
657         LyXTextClass const & tclass = params.getLyXTextClass();
658         docstring trmarg = from_utf8(tclass.rightmargin());
659         docstring lrmarg = from_utf8(par.layout()->rightmargin);
660         FontMetrics const & fm = theFontMetrics(params.getFont());
661         int const r_margin =
662                 lyx::rightMargin()
663                 + fm.signedWidth(trmarg)
664                 + fm.signedWidth(lrmarg)
665                 * 4 / (par.getDepth() + 4);
666
667         return r_margin;
668 }
669
670
671 int LyXText::labelEnd(Buffer const & buffer, pit_type const pit) const
672 {
673         // labelEnd is only needed if the layout fills a flushleft label.
674         if (pars_[pit].layout()->margintype != MARGIN_MANUAL)
675                 return 0;
676         // return the beginning of the body
677         return leftMargin(buffer, pit);
678 }
679
680
681 namespace {
682
683 // this needs special handling - only newlines count as a break point
684 pos_type addressBreakPoint(pos_type i, Paragraph const & par)
685 {
686         pos_type const end = par.size();
687
688         for (; i < end; ++i)
689                 if (par.isNewline(i))
690                         return i + 1;
691
692         return end;
693 }
694
695 };
696
697
698 void LyXText::rowBreakPoint(Buffer const & buffer, int right_margin,
699                 pit_type const pit,     Row & row) const
700 {
701         Paragraph const & par = pars_[pit];
702         pos_type const end = par.size();
703         pos_type const pos = row.pos();
704         if (pos == end) {
705                 row.endpos(end);
706                 return;
707         }
708
709         // maximum pixel width of a row
710         int width = maxwidth_ - right_margin; // - leftMargin(buffer, pit, row);
711         if (width < 0) {
712                 row.endpos(end);
713                 return;
714         }
715
716         LyXLayout_ptr const & layout = par.layout();
717
718         if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
719                 row.endpos(addressBreakPoint(pos, par));
720                 return;
721         }
722
723         pos_type const body_pos = par.beginOfBody();
724
725
726         // Now we iterate through until we reach the right margin
727         // or the end of the par, then choose the possible break
728         // nearest that.
729
730         int const left = leftMargin(buffer, pit, pos);
731         int x = left;
732
733         // pixel width since last breakpoint
734         int chunkwidth = 0;
735
736         FontIterator fi = FontIterator(buffer, *this, par, pos);
737         pos_type point = end;
738         pos_type i = pos;
739         FontMetrics const & fm = theFontMetrics(getLabelFont(buffer, par));
740         for ( ; i < end; ++i, ++fi) {
741                 char_type const c = par.getChar(i);
742                 int thiswidth = singleWidth(par, i, c, *fi);
743
744                 // add the auto-hfill from label end to the body
745                 if (body_pos && i == body_pos) {
746                         docstring lsep = from_utf8(layout->labelsep);
747                         int add = fm.width(lsep);
748                         if (par.isLineSeparator(i - 1))
749                                 add -= singleWidth(buffer, par, i - 1);
750
751                         add = std::max(add, labelEnd(buffer, pit) - x);
752                         thiswidth += add;
753                 }
754
755                 x += thiswidth;
756                 chunkwidth += thiswidth;
757
758                 // break before a character that will fall off
759                 // the right of the row
760                 if (x >= width) {
761                         // if no break before, break here
762                         if (point == end || chunkwidth >= width - left) {
763                                 if (i > pos)
764                                         point = i;
765                                 else
766                                         point = i + 1;
767
768                         }
769                         // exit on last registered breakpoint:
770                         break;
771                 }
772
773                 if (par.isNewline(i)) {
774                         point = i + 1;
775                         break;
776                 }
777                 // Break before...
778                 if (i + 1 < end) {
779                         if (par.isInset(i + 1) && par.getInset(i + 1)->display()) {
780                                 point = i + 1;
781                                 break;
782                         }
783                         // ...and after.
784                         if (par.isInset(i) && par.getInset(i)->display()) {
785                                 point = i + 1;
786                                 break;
787                         }
788                 }
789
790                 if (!par.isInset(i) || par.getInset(i)->isChar()) {
791                         // some insets are line separators too
792                         if (par.isLineSeparator(i)) {
793                                 // register breakpoint:
794                                 point = i + 1;
795                                 chunkwidth = 0;
796                         }
797                 }
798         }
799
800         // maybe found one, but the par is short enough.
801         if (i == end && x < width)
802                 point = end;
803
804         // manual labels cannot be broken in LaTeX. But we
805         // want to make our on-screen rendering of footnotes
806         // etc. still break
807         if (body_pos && point < body_pos)
808                 point = body_pos;
809
810         row.endpos(point);
811 }
812
813
814 void LyXText::setRowWidth(Buffer const & buffer, pit_type const pit, Row & row) const
815 {
816         // get the pure distance
817         pos_type const end = row.endpos();
818
819         Paragraph const & par = pars_[pit];
820         docstring const labelsep = from_utf8(par.layout()->labelsep);
821         int w = leftMargin(buffer, pit, row.pos());
822
823         pos_type const body_pos = par.beginOfBody();
824         pos_type i = row.pos();
825
826         FontMetrics const & fm = theFontMetrics(getLabelFont(buffer, par));
827
828         if (i < end) {
829                 FontIterator fi = FontIterator(buffer, *this, par, i);
830                 for ( ; i < end; ++i, ++fi) {
831                         if (body_pos > 0 && i == body_pos) {
832                                 w += fm.width(labelsep);
833                                 if (par.isLineSeparator(i - 1))
834                                         w -= singleWidth(buffer, par, i - 1);
835                                 w = max(w, labelEnd(buffer, pit));
836                         }
837                         char_type const c = par.getChar(i);
838                         w += singleWidth(par, i, c, *fi);
839                 }
840         }
841
842         if (body_pos > 0 && body_pos >= end) {
843                 w += fm.width(labelsep);
844                 if (end > 0 && par.isLineSeparator(end - 1))
845                         w -= singleWidth(buffer, par, end - 1);
846                 w = max(w, labelEnd(buffer, pit));
847         }
848
849         row.width(w + rightMargin(buffer, par));
850 }
851
852
853 // returns the minimum space a manual label needs on the screen in pixel
854 int LyXText::labelFill(Buffer const & buffer, Paragraph const & par,
855                 Row const & row) const
856 {
857         pos_type last = par.beginOfBody();
858
859         BOOST_ASSERT(last > 0);
860
861         // -1 because a label ends with a space that is in the label
862         --last;
863
864         // a separator at this end does not count
865         if (par.isLineSeparator(last))
866                 --last;
867
868         int w = 0;
869         for (pos_type i = row.pos(); i <= last; ++i)
870                 w += singleWidth(buffer, par, i);
871
872         docstring const & label = par.params().labelWidthString();
873         if (label.empty())
874                 return 0;
875
876         FontMetrics const & fm = theFontMetrics(getLabelFont(buffer, par));
877
878         return max(0, fm.width(label) - w);
879 }
880
881
882 LColor_color LyXText::backgroundColor() const
883 {
884         return LColor_color(LColor::color(background_color_));
885 }
886
887
888 void LyXText::setHeightOfRow(BufferView const & bv, pit_type const pit,
889                 Row & row)
890 {
891         Paragraph const & par = pars_[pit];
892         // get the maximum ascent and the maximum descent
893         double layoutasc = 0;
894         double layoutdesc = 0;
895         double const dh = defaultRowHeight();
896
897         // ok, let us initialize the maxasc and maxdesc value.
898         // Only the fontsize count. The other properties
899         // are taken from the layoutfont. Nicer on the screen :)
900         LyXLayout_ptr const & layout = par.layout();
901
902         // as max get the first character of this row then it can
903         // increase but not decrease the height. Just some point to
904         // start with so we don't have to do the assignment below too
905         // often.
906         Buffer const & buffer = *bv.buffer();
907         LyXFont font = getFont(buffer, par, row.pos());
908         LyXFont::FONT_SIZE const tmpsize = font.size();
909         font = getLayoutFont(buffer, pit);
910         LyXFont::FONT_SIZE const size = font.size();
911         font.setSize(tmpsize);
912
913         LyXFont labelfont = getLabelFont(buffer, par);
914
915         FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
916         FontMetrics const & fontmetrics = theFontMetrics(font);
917
918         // these are minimum values
919         double const spacing_val = layout->spacing.getValue()
920                 * spacing(*bv.buffer(), par);
921         //lyxerr << "spacing_val = " << spacing_val << endl;
922         int maxasc  = int(fontmetrics.maxAscent()  * spacing_val);
923         int maxdesc = int(fontmetrics.maxDescent() * spacing_val);
924
925         // insets may be taller
926         InsetList::const_iterator ii = par.insetlist.begin();
927         InsetList::const_iterator iend = par.insetlist.end();
928         for ( ; ii != iend; ++ii) {
929                 if (ii->pos >= row.pos() && ii->pos < row.endpos()) {
930                         maxasc  = max(maxasc,  ii->inset->ascent());
931                         maxdesc = max(maxdesc, ii->inset->descent());
932                 }
933         }
934
935         // Check if any custom fonts are larger (Asger)
936         // This is not completely correct, but we can live with the small,
937         // cosmetic error for now.
938         int labeladdon = 0;
939         pos_type const pos_end = row.endpos();
940
941         LyXFont::FONT_SIZE maxsize =
942                 par.highestFontInRange(row.pos(), pos_end, size);
943         if (maxsize > font.size()) {
944                 font.setSize(maxsize);
945                 maxasc  = max(maxasc,  fontmetrics.maxAscent());
946                 maxdesc = max(maxdesc, fontmetrics.maxDescent());
947         }
948
949         // This is nicer with box insets:
950         ++maxasc;
951         ++maxdesc;
952
953         row.ascent(maxasc);
954
955         // is it a top line?
956         if (row.pos() == 0) {
957                 Buffer const & buffer = *bv.buffer();
958                 BufferParams const & bufparams = buffer.params();
959                 // some parksips VERY EASY IMPLEMENTATION
960                 if (bufparams.paragraph_separation
961                     == BufferParams::PARSEP_SKIP
962                         && pit != 0
963                         && ((layout->isParagraph() && par.getDepth() == 0)
964                             || (pars_[pit - 1].layout()->isParagraph()
965                                 && pars_[pit - 1].getDepth() == 0)))
966                 {
967                                 maxasc += bufparams.getDefSkip().inPixels(bv);
968                 }
969
970                 if (par.params().startOfAppendix())
971                         maxasc += int(3 * dh);
972
973                 // This is special code for the chapter, since the label of this
974                 // layout is printed in an extra row
975                 if (layout->counter == "chapter"
976                     && !par.params().labelString().empty()) {
977                         labeladdon = int(labelfont_metrics.maxHeight()
978                                      * layout->spacing.getValue()
979                                      * spacing(buffer, par));
980                 }
981
982                 // special code for the top label
983                 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
984                      || layout->labeltype == LABEL_BIBLIO
985                      || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
986                     && isFirstInSequence(pit, paragraphs())
987                     && !par.getLabelstring().empty())
988                 {
989                         labeladdon = int(
990                                   labelfont_metrics.maxHeight()
991                                         * layout->spacing.getValue()
992                                         * spacing(*bv.buffer(), par)
993                                 + (layout->topsep + layout->labelbottomsep) * dh);
994                 }
995
996                 // Add the layout spaces, for example before and after
997                 // a section, or between the items of a itemize or enumerate
998                 // environment.
999
1000                 pit_type prev = depthHook(pit, pars_, par.getDepth());
1001                 if (prev != pit
1002                     && pars_[prev].layout() == layout
1003                     && pars_[prev].getDepth() == par.getDepth()
1004                     && pars_[prev].getLabelWidthString() == par.getLabelWidthString())
1005                 {
1006                         layoutasc = layout->itemsep * dh;
1007                 } else if (pit != 0 || row.pos() != 0) {
1008                         if (layout->topsep > 0)
1009                                 layoutasc = layout->topsep * dh;
1010                 }
1011
1012                 prev = outerHook(pit, pars_);
1013                 if (prev != pit_type(pars_.size())) {
1014                         maxasc += int(pars_[prev].layout()->parsep * dh);
1015                 } else if (pit != 0) {
1016                         if (pars_[pit - 1].getDepth() != 0 ||
1017                                         pars_[pit - 1].layout() == layout) {
1018                                 maxasc += int(layout->parsep * dh);
1019                         }
1020                 }
1021         }
1022
1023         // is it a bottom line?
1024         if (row.endpos() >= par.size()) {
1025                 // add the layout spaces, for example before and after
1026                 // a section, or between the items of a itemize or enumerate
1027                 // environment
1028                 pit_type nextpit = pit + 1;
1029                 if (nextpit != pit_type(pars_.size())) {
1030                         pit_type cpit = pit;
1031                         double usual = 0;
1032                         double unusual = 0;
1033
1034                         if (pars_[cpit].getDepth() > pars_[nextpit].getDepth()) {
1035                                 usual = pars_[cpit].layout()->bottomsep * dh;
1036                                 cpit = depthHook(cpit, paragraphs(), pars_[nextpit].getDepth());
1037                                 if (pars_[cpit].layout() != pars_[nextpit].layout()
1038                                         || pars_[nextpit].getLabelWidthString() != pars_[cpit].getLabelWidthString())
1039                                 {
1040                                         unusual = pars_[cpit].layout()->bottomsep * dh;
1041                                 }
1042                                 layoutdesc = max(unusual, usual);
1043                         } else if (pars_[cpit].getDepth() == pars_[nextpit].getDepth()) {
1044                                 if (pars_[cpit].layout() != pars_[nextpit].layout()
1045                                         || pars_[nextpit].getLabelWidthString() != pars_[cpit].getLabelWidthString())
1046                                         layoutdesc = int(pars_[cpit].layout()->bottomsep * dh);
1047                         }
1048                 }
1049         }
1050
1051         // incalculate the layout spaces
1052         maxasc  += int(layoutasc  * 2 / (2 + pars_[pit].getDepth()));
1053         maxdesc += int(layoutdesc * 2 / (2 + pars_[pit].getDepth()));
1054
1055         // FIXME: the correct way is to do the following is to move the 
1056         // following code in another method specially tailored for the 
1057         // main LyXText. The following test is thus bogus.
1058         LyXText const & text = buffer.text();
1059         // Top and bottom margin of the document (only at top-level)
1060         if (&text == this) {
1061                 if (pit == 0 && row.pos() == 0)
1062                         maxasc += 20;
1063                 if (pit + 1 == pit_type(pars_.size()) &&
1064                     row.endpos() == par.size())
1065                         maxdesc += 20;
1066         }
1067
1068         row.ascent(maxasc + labeladdon);
1069         row.descent(maxdesc);
1070 }
1071
1072
1073 namespace {
1074
1075 }
1076
1077 void LyXText::breakParagraph(LCursor & cur, bool keep_layout)
1078 {
1079         BOOST_ASSERT(this == cur.text());
1080
1081         Paragraph & cpar = cur.paragraph();
1082         pit_type cpit = cur.pit();
1083
1084         LyXTextClass const & tclass = cur.buffer().params().getLyXTextClass();
1085         LyXLayout_ptr const & layout = cpar.layout();
1086
1087         // this is only allowed, if the current paragraph is not empty
1088         // or caption and if it has not the keepempty flag active
1089         if (cur.lastpos() == 0 && !cpar.allowEmpty()
1090            && layout->labeltype != LABEL_SENSITIVE)
1091                 return;
1092
1093         // a layout change may affect also the following paragraph
1094         recUndo(cur, cur.pit(), undoSpan(cur.pit()) - 1);
1095
1096         // Always break behind a space
1097         // It is better to erase the space (Dekel)
1098         if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
1099                 // FIXME: change tracking (MG)
1100                 cpar.eraseChar(cur.pos(), cur.buffer().params().trackChanges);
1101
1102         // How should the layout for the new paragraph be?
1103         int preserve_layout = 0;
1104         if (keep_layout)
1105                 preserve_layout = 2;
1106         else
1107                 preserve_layout = layout->isEnvironment();
1108
1109         // We need to remember this before we break the paragraph, because
1110         // that invalidates the layout variable
1111         bool sensitive = layout->labeltype == LABEL_SENSITIVE;
1112
1113         // we need to set this before we insert the paragraph.
1114         bool const isempty = cpar.allowEmpty() && cpar.empty();
1115
1116         lyx::breakParagraph(cur.buffer().params(), paragraphs(), cpit,
1117                          cur.pos(), preserve_layout);
1118
1119         // After this, neither paragraph contains any rows!
1120
1121         cpit = cur.pit();
1122         pit_type next_par = cpit + 1;
1123
1124         // well this is the caption hack since one caption is really enough
1125         if (sensitive) {
1126                 if (cur.pos() == 0)
1127                         // set to standard-layout
1128                         pars_[cpit].applyLayout(tclass.defaultLayout());
1129                 else
1130                         // set to standard-layout
1131                         pars_[next_par].applyLayout(tclass.defaultLayout());
1132         }
1133
1134         while (!pars_[next_par].empty() && pars_[next_par].isNewline(0))
1135                 // FIXME: change tracking (MG)
1136                 pars_[next_par].eraseChar(0, cur.buffer().params().trackChanges);
1137
1138         ParIterator current_it(cur);
1139         ParIterator last_it(cur);
1140         ++last_it;
1141         ++last_it;
1142
1143         updateLabels(cur.buffer(), current_it, last_it);
1144
1145         // Mark "carriage return" as inserted if change tracking:
1146         if (cur.buffer().params().trackChanges) {
1147                 // FIXME: Change tracking (MG)
1148                 cur.paragraph().setChange(cur.paragraph().size(),
1149                         Change(Change::INSERTED));
1150         }
1151
1152         // FIXME: Breaking a paragraph has nothing to do with setting a cursor.
1153         // Because of the mix between the model (the paragraph contents) and the
1154         // view (the paragraph breaking in rows, we have to do this here before
1155         // the setCursor() call below.
1156         bool changed_height = redoParagraph(cur.bv(), cpit);
1157         changed_height |= redoParagraph(cur.bv(), cpit + 1);
1158         if (changed_height)
1159                 // A singlePar update is not enough in this case.
1160                 cur.updateFlags(Update::Force);
1161
1162
1163         // This check is necessary. Otherwise the new empty paragraph will
1164         // be deleted automatically. And it is more friendly for the user!
1165         if (cur.pos() != 0 || isempty)
1166                 setCursor(cur, cur.pit() + 1, 0);
1167         else
1168                 setCursor(cur, cur.pit(), 0);
1169 }
1170
1171
1172 // insert a character, moves all the following breaks in the
1173 // same Paragraph one to the right and make a rebreak
1174 void LyXText::insertChar(LCursor & cur, char_type c)
1175 {
1176         BOOST_ASSERT(this == cur.text());
1177         BOOST_ASSERT(c != Paragraph::META_INSET);
1178
1179         recordUndo(cur, Undo::INSERT);
1180
1181         Buffer const & buffer = cur.buffer();
1182         Paragraph & par = cur.paragraph();
1183         // try to remove this
1184         pit_type const pit = cur.pit();
1185
1186         bool const freeSpacing = par.layout()->free_spacing ||
1187                 par.isFreeSpacing();
1188
1189         if (lyxrc.auto_number) {
1190                 static docstring const number_operators = from_ascii("+-/*");
1191                 static docstring const number_unary_operators = from_ascii("+-");
1192                 static docstring const number_seperators = from_ascii(".,:");
1193
1194                 if (current_font.number() == LyXFont::ON) {
1195                         if (!isDigit(c) && !contains(number_operators, c) &&
1196                             !(contains(number_seperators, c) &&
1197                               cur.pos() != 0 &&
1198                               cur.pos() != cur.lastpos() &&
1199                               getFont(buffer, par, cur.pos()).number() == LyXFont::ON &&
1200                               getFont(buffer, par, cur.pos() - 1).number() == LyXFont::ON)
1201                            )
1202                                 number(cur); // Set current_font.number to OFF
1203                 } else if (isDigit(c) &&
1204                            real_current_font.isVisibleRightToLeft()) {
1205                         number(cur); // Set current_font.number to ON
1206
1207                         if (cur.pos() != 0) {
1208                                 char_type const c = par.getChar(cur.pos() - 1);
1209                                 if (contains(number_unary_operators, c) &&
1210                                     (cur.pos() == 1
1211                                      || par.isSeparator(cur.pos() - 2)
1212                                      || par.isNewline(cur.pos() - 2))
1213                                   ) {
1214                                         setCharFont(buffer, pit, cur.pos() - 1, current_font);
1215                                 } else if (contains(number_seperators, c)
1216                                      && cur.pos() >= 2
1217                                      && getFont(buffer, par, cur.pos() - 2).number() == LyXFont::ON) {
1218                                         setCharFont(buffer, pit, cur.pos() - 1, current_font);
1219                                 }
1220                         }
1221                 }
1222         }
1223
1224         // First check, if there will be two blanks together or a blank at
1225         // the beginning of a paragraph.
1226         // I decided to handle blanks like normal characters, the main
1227         // difference are the special checks when calculating the row.fill
1228         // (blank does not count at the end of a row) and the check here
1229
1230         // When the free-spacing option is set for the current layout,
1231         // disable the double-space checking
1232         if (!freeSpacing && isLineSeparatorChar(c)) {
1233                 if (cur.pos() == 0) {
1234                         static bool sent_space_message = false;
1235                         if (!sent_space_message) {
1236                                 cur.message(_("You cannot insert a space at the "
1237                                                            "beginning of a paragraph. Please read the Tutorial."));
1238                                 sent_space_message = true;
1239                         }
1240                         return;
1241                 }
1242                 BOOST_ASSERT(cur.pos() > 0);
1243                 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
1244                     && !par.isDeleted(cur.pos() - 1)) {
1245                         static bool sent_space_message = false;
1246                         if (!sent_space_message) {
1247                                 cur.message(_("You cannot type two spaces this way. "
1248                                                            "Please read the Tutorial."));
1249                                 sent_space_message = true;
1250                         }
1251                         return;
1252                 }
1253         }
1254
1255         par.insertChar(cur.pos(), c, current_font, cur.buffer().params().trackChanges);
1256
1257         // FIXME: Inserting a character has nothing to do with setting a cursor.
1258         // Because of the mix between the model (the paragraph contents) and the
1259         // view (the paragraph breaking in rows, we have to do this here.
1260         if (redoParagraph(cur.bv(), cur.pit()))
1261                 // A singlePar update is not enough in this case.
1262                 cur.updateFlags(Update::Force);
1263         setCursor(cur, cur.pit(), cur.pos() + 1, false, cur.boundary());
1264         charInserted();
1265 }
1266
1267
1268 void LyXText::charInserted()
1269 {
1270         // Here we call finishUndo for every 20 characters inserted.
1271         // This is from my experience how emacs does it. (Lgb)
1272         static unsigned int counter;
1273         if (counter < 20) {
1274                 ++counter;
1275         } else {
1276                 finishUndo();
1277                 counter = 0;
1278         }
1279 }
1280
1281
1282 RowMetrics LyXText::computeRowMetrics(Buffer const & buffer,
1283                 pit_type const pit, Row const & row) const
1284 {
1285         RowMetrics result;
1286         Paragraph const & par = pars_[pit];
1287
1288         double w = dim_.wid - row.width();
1289
1290         bool const is_rtl = isRTL(buffer, par);
1291         if (is_rtl)
1292                 result.x = rightMargin(buffer, par);
1293         else
1294                 result.x = leftMargin(buffer, pit, row.pos());
1295
1296         // is there a manual margin with a manual label
1297         LyXLayout_ptr const & layout = par.layout();
1298
1299         if (layout->margintype == MARGIN_MANUAL
1300             && layout->labeltype == LABEL_MANUAL) {
1301                 /// We might have real hfills in the label part
1302                 int nlh = numberOfLabelHfills(par, row);
1303
1304                 // A manual label par (e.g. List) has an auto-hfill
1305                 // between the label text and the body of the
1306                 // paragraph too.
1307                 // But we don't want to do this auto hfill if the par
1308                 // is empty.
1309                 if (!par.empty())
1310                         ++nlh;
1311
1312                 if (nlh && !par.getLabelWidthString().empty())
1313                         result.label_hfill = labelFill(buffer, par, row) / double(nlh);
1314         }
1315
1316         // are there any hfills in the row?
1317         int const nh = numberOfHfills(par, row);
1318
1319         if (nh) {
1320                 if (w > 0)
1321                         result.hfill = w / nh;
1322         // we don't have to look at the alignment if it is ALIGN_LEFT and
1323         // if the row is already larger then the permitted width as then
1324         // we force the LEFT_ALIGN'edness!
1325         } else if (int(row.width()) < maxwidth_) {
1326                 // is it block, flushleft or flushright?
1327                 // set x how you need it
1328                 int align;
1329                 if (par.params().align() == LYX_ALIGN_LAYOUT)
1330                         align = layout->align;
1331                 else
1332                         align = par.params().align();
1333
1334                 // Display-style insets should always be on a centred row
1335                 // The test on par.size() is to catch zero-size pars, which
1336                 // would trigger the assert in Paragraph::getInset().
1337                 //inset = par.size() ? par.getInset(row.pos()) : 0;
1338                 if (!par.empty()
1339                     && par.isInset(row.pos())
1340                     && par.getInset(row.pos())->display())
1341                 {
1342                         align = LYX_ALIGN_CENTER;
1343                 }
1344
1345                 switch (align) {
1346                 case LYX_ALIGN_BLOCK: {
1347                         int const ns = numberOfSeparators(par, row);
1348                         bool disp_inset = false;
1349                         if (row.endpos() < par.size()) {
1350                                 InsetBase const * in = par.getInset(row.endpos());
1351                                 if (in)
1352                                         disp_inset = in->display();
1353                         }
1354                         // If we have separators, this is not the last row of a
1355                         // par, does not end in newline, and is not row above a
1356                         // display inset... then stretch it
1357                         if (ns
1358                             && row.endpos() < par.size()
1359                             && !par.isNewline(row.endpos() - 1)
1360                             && !disp_inset
1361                                 ) {
1362                                 result.separator = w / ns;
1363                         } else if (is_rtl) {
1364                                 result.x += w;
1365                         }
1366                         break;
1367                 }
1368                 case LYX_ALIGN_RIGHT:
1369                         result.x += w;
1370                         break;
1371                 case LYX_ALIGN_CENTER:
1372                         result.x += w / 2;
1373                         break;
1374                 }
1375         }
1376
1377         bidi.computeTables(par, buffer, row);
1378         if (is_rtl) {
1379                 pos_type body_pos = par.beginOfBody();
1380                 pos_type end = row.endpos();
1381
1382                 if (body_pos > 0
1383                     && (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1384                 {
1385                         docstring const lsep = from_utf8(layout->labelsep);
1386                         result.x += theFontMetrics(getLabelFont(buffer, par)).width(lsep);
1387                         if (body_pos <= end)
1388                                 result.x += result.label_hfill;
1389                 }
1390         }
1391
1392         return result;
1393 }
1394
1395
1396 // the cursor set functions have a special mechanism. When they
1397 // realize, that you left an empty paragraph, they will delete it.
1398
1399 bool LyXText::cursorRightOneWord(LCursor & cur)
1400 {
1401         BOOST_ASSERT(this == cur.text());
1402
1403         LCursor old = cur;
1404
1405         if (old.pos() == old.lastpos() && old.pit() != old.lastpit()) {
1406                 ++old.pit();
1407                 old.pos() = 0;
1408         } else {
1409                 // Advance through word.
1410                 while (old.pos() != old.lastpos() && old.paragraph().isLetter(old.pos()))
1411                         ++old.pos();
1412                 // Skip through trailing nonword stuff.
1413                 while (old.pos() != old.lastpos() && !old.paragraph().isLetter(old.pos()))
1414                         ++old.pos();
1415         }
1416         return setCursor(cur, old.pit(), old.pos());
1417 }
1418
1419
1420 bool LyXText::cursorLeftOneWord(LCursor & cur)
1421 {
1422         BOOST_ASSERT(this == cur.text());
1423
1424         LCursor old = cur;
1425
1426         if (old.pos() == 0 && old.pit() != 0) {
1427                 --old.pit();
1428                 old.pos() = old.lastpos();
1429         } else {
1430                 // Skip through initial nonword stuff.
1431                 while (old.pos() != 0 && !old.paragraph().isLetter(old.pos() - 1))
1432                         --old.pos();
1433                 // Advance through word.
1434                 while (old.pos() != 0 && old.paragraph().isLetter(old.pos() - 1))
1435                         --old.pos();
1436         }
1437         return setCursor(cur, old.pit(), old.pos());
1438 }
1439
1440
1441 void LyXText::selectWord(LCursor & cur, word_location loc)
1442 {
1443         BOOST_ASSERT(this == cur.text());
1444         CursorSlice from = cur.top();
1445         CursorSlice to = cur.top();
1446         getWord(from, to, loc);
1447         if (cur.top() != from)
1448                 setCursor(cur, from.pit(), from.pos());
1449         if (to == from)
1450                 return;
1451         cur.resetAnchor();
1452         setCursor(cur, to.pit(), to.pos());
1453         cur.setSelection();
1454 }
1455
1456
1457 // Select the word currently under the cursor when no
1458 // selection is currently set
1459 bool LyXText::selectWordWhenUnderCursor(LCursor & cur, word_location loc)
1460 {
1461         BOOST_ASSERT(this == cur.text());
1462         if (cur.selection())
1463                 return false;
1464         selectWord(cur, loc);
1465         return cur.selection();
1466 }
1467
1468
1469 void LyXText::acceptChange(LCursor & cur)
1470 {
1471         BOOST_ASSERT(this == cur.text());
1472         if (!cur.selection() && cur.lastpos() != 0)
1473                 return;
1474
1475         recordUndoSelection(cur, Undo::INSERT);
1476
1477         DocIterator it = cur.selectionBegin();
1478         DocIterator et = cur.selectionEnd();
1479         pit_type pit = it.pit();
1480         bool isDeleted = pars_[pit].isDeleted(it.pos());
1481         for (; pit <= et.pit(); ++pit) {
1482                 pos_type left  = ( pit == it.pit() ? it.pos() : 0 );
1483                 pos_type right =
1484                     ( pit == et.pit() ? et.pos() : pars_[pit].size() + 1 );
1485                 pars_[pit].acceptChanges(left, right);
1486         }
1487         if (isDeleted) {
1488                 ParagraphList & plist = paragraphs();
1489                 if (it.pit() + 1 < et.pit())
1490                         pars_.erase(boost::next(plist.begin(), it.pit() + 1),
1491                                     boost::next(plist.begin(), et.pit()));
1492
1493                 // Paragraph merge if appropriate:
1494                 // FIXME: change tracking (MG)
1495                 if (pars_[it.pit()].isDeleted(pars_[it.pit()].size())) {
1496                         setCursorIntern(cur, it.pit() + 1, 0);
1497                         backspacePos0(cur);
1498                 }
1499         }
1500         finishUndo();
1501         cur.clearSelection();
1502         setCursorIntern(cur, it.pit(), 0);
1503 }
1504
1505
1506 void LyXText::rejectChange(LCursor & cur)
1507 {
1508         BOOST_ASSERT(this == cur.text());
1509         if (!cur.selection() && cur.lastpos() != 0)
1510                 return;
1511
1512         recordUndoSelection(cur, Undo::INSERT);
1513
1514         DocIterator it = cur.selectionBegin();
1515         DocIterator et = cur.selectionEnd();
1516         pit_type pit = it.pit();
1517         bool isInserted = pars_[pit].isInserted(it.pos());
1518         for (; pit <= et.pit(); ++pit) {
1519                 pos_type left  = ( pit == it.pit() ? it.pos() : 0 );
1520                 pos_type right =
1521                     ( pit == et.pit() ? et.pos() : pars_[pit].size() + 1 );
1522                 pars_[pit].rejectChanges(left, right);
1523         }
1524         if (isInserted) {
1525                 ParagraphList & plist = paragraphs();
1526                 if (it.pit() + 1 < et.pit())
1527                         pars_.erase(boost::next(plist.begin(), it.pit() + 1),
1528                                     boost::next(plist.begin(), et.pit()));
1529                 // Paragraph merge if appropriate:
1530                 // FIXME: change tracking (MG)
1531                 if (pars_[it.pit()].isInserted(pars_[it.pit()].size())) {
1532                         setCursorIntern(cur, it.pit() + 1, 0);
1533                         backspacePos0(cur);
1534                 }
1535         }
1536         finishUndo();
1537         cur.clearSelection();
1538         setCursorIntern(cur, it.pit(), 0);
1539 }
1540
1541
1542 // Delete from cursor up to the end of the current or next word.
1543 void LyXText::deleteWordForward(LCursor & cur)
1544 {
1545         BOOST_ASSERT(this == cur.text());
1546         if (cur.lastpos() == 0)
1547                 cursorRight(cur);
1548         else {
1549                 cur.resetAnchor();
1550                 cur.selection() = true;
1551                 cursorRightOneWord(cur);
1552                 cur.setSelection();
1553                 cutSelection(cur, true, false);
1554         }
1555 }
1556
1557
1558 // Delete from cursor to start of current or prior word.
1559 void LyXText::deleteWordBackward(LCursor & cur)
1560 {
1561         BOOST_ASSERT(this == cur.text());
1562         if (cur.lastpos() == 0)
1563                 cursorLeft(cur);
1564         else {
1565                 cur.resetAnchor();
1566                 cur.selection() = true;
1567                 cursorLeftOneWord(cur);
1568                 cur.setSelection();
1569                 cutSelection(cur, true, false);
1570         }
1571 }
1572
1573
1574 // Kill to end of line.
1575 void LyXText::deleteLineForward(LCursor & cur)
1576 {
1577         BOOST_ASSERT(this == cur.text());
1578         if (cur.lastpos() == 0) {
1579                 // Paragraph is empty, so we just go to the right
1580                 cursorRight(cur);
1581         } else {
1582                 cur.resetAnchor();
1583                 cur.selection() = true; // to avoid deletion
1584                 cursorEnd(cur);
1585                 cur.setSelection();
1586                 // What is this test for ??? (JMarc)
1587                 if (!cur.selection())
1588                         deleteWordForward(cur);
1589                 else
1590                         cutSelection(cur, true, false);
1591         }
1592 }
1593
1594
1595 void LyXText::changeCase(LCursor & cur, LyXText::TextCase action)
1596 {
1597         BOOST_ASSERT(this == cur.text());
1598         CursorSlice from;
1599         CursorSlice to;
1600
1601         if (cur.selection()) {
1602                 from = cur.selBegin();
1603                 to = cur.selEnd();
1604         } else {
1605                 from = cur.top();
1606                 getWord(from, to, PARTIAL_WORD);
1607                 cursorRightOneWord(cur);
1608         }
1609
1610         recordUndoSelection(cur);
1611
1612         pos_type pos = from.pos();
1613         int par = from.pit();
1614
1615         while (par != int(pars_.size()) && (pos != to.pos() || par != to.pit())) {
1616                 pit_type pit = par;
1617                 if (pos == pars_[pit].size()) {
1618                         ++par;
1619                         pos = 0;
1620                         continue;
1621                 }
1622                 char_type c = pars_[pit].getChar(pos);
1623                 if (c != Paragraph::META_INSET) {
1624                         switch (action) {
1625                         case text_lowercase:
1626                                 c = lowercase(c);
1627                                 break;
1628                         case text_capitalization:
1629                                 c = uppercase(c);
1630                                 action = text_lowercase;
1631                                 break;
1632                         case text_uppercase:
1633                                 c = uppercase(c);
1634                                 break;
1635                         }
1636                 }
1637
1638                 // FIXME: change tracking (MG)
1639                 // sorry but we are no longer allowed to set a single character directly
1640                 // we have to rewrite this method in terms of erase&insert operations
1641                 //pars_[pit].setChar(pos, c);
1642                 ++pos;
1643         }
1644 }
1645
1646
1647 bool LyXText::erase(LCursor & cur)
1648 {
1649         BOOST_ASSERT(this == cur.text());
1650         bool needsUpdate = false;
1651         Paragraph & par = cur.paragraph();
1652
1653         if (cur.pos() != cur.lastpos()) {
1654                 // this is the code for a normal delete, not pasting
1655                 // any paragraphs
1656                 recordUndo(cur, Undo::DELETE);
1657                 par.eraseChar(cur.pos(), cur.buffer().params().trackChanges);
1658                 if (par.isDeleted(cur.pos()))
1659                         cur.forwardPosNoDescend();
1660                 needsUpdate = true;
1661         } else if (cur.pit() != cur.lastpit()) {
1662                 if (cur.buffer().params().trackChanges
1663                     && par.isInserted(cur.pos())) {
1664                         // mark "carriage return" as deleted:
1665                         // FIXME: Change tracking (MG)
1666                         par.setChange(cur.pos(), Change(Change::DELETED));
1667                         cur.forwardPos();
1668                         needsUpdate = true;
1669                 } else {
1670                         setCursorIntern(cur, cur.pit() + 1, 0);
1671                         needsUpdate = backspacePos0(cur);
1672                         // FIXME: Change tracking (MG)
1673                         if (cur.paragraph().isDeleted(cur.pos()))
1674                                 cur.forwardPos();
1675                 }
1676         } else
1677                 needsUpdate = dissolveInset(cur);
1678
1679         // FIXME: Inserting characters has nothing to do with setting a cursor.
1680         // Because of the mix between the model (the paragraph contents)
1681         // and the view (the paragraph breaking in rows, we have to do this
1682         // here before the setCursorIntern() call.
1683         if (needsUpdate) {
1684                 if (redoParagraph(cur.bv(), cur.pit()))
1685                         // A singlePar update is not enough in this case.
1686                         cur.updateFlags(Update::Force);
1687                 // Make sure the cursor is correct. Is this really needed?
1688                 // No, not really... at least not here!
1689                 cur.text()->setCursorIntern(cur, cur.pit(), cur.pos());
1690         }
1691         
1692         return needsUpdate;
1693 }
1694
1695
1696 bool LyXText::backspacePos0(LCursor & cur)
1697 {
1698         BOOST_ASSERT(this == cur.text());
1699         if (cur.pit() == 0)
1700                 return false;
1701
1702         bool needsUpdate = false;
1703
1704         BufferParams const & bufparams = cur.buffer().params();
1705         LyXTextClass const & tclass = bufparams.getLyXTextClass();
1706         ParagraphList & plist = cur.text()->paragraphs();
1707         Paragraph const & par = cur.paragraph();
1708         LCursor prevcur = cur;
1709         --prevcur.pit();
1710         prevcur.pos() = prevcur.lastpos();
1711         Paragraph const & prevpar = prevcur.paragraph();
1712
1713         // is it an empty paragraph?
1714         if (cur.lastpos() == 0 
1715             || (cur.lastpos() == 1 && par.isSeparator(0))) {
1716                 recordUndo(cur, Undo::ATOMIC, prevcur.pit(), cur.pit());
1717                 plist.erase(boost::next(plist.begin(), cur.pit()));
1718                 needsUpdate = true;
1719         }
1720         // is previous par empty?
1721         else if (prevcur.lastpos() == 0 
1722                  || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
1723                 recordUndo(cur, Undo::ATOMIC, prevcur.pit(), cur.pit());
1724                 plist.erase(boost::next(plist.begin(), prevcur.pit()));
1725                 needsUpdate = true;
1726         }
1727         // Pasting is not allowed, if the paragraphs have different
1728         // layout. I think it is a real bug of all other
1729         // word processors to allow it. It confuses the user.
1730         // Correction: Pasting is always allowed with standard-layout
1731         else if (par.layout() == prevpar.layout()
1732                  || par.layout() == tclass.defaultLayout()) {
1733                 recordUndo(cur, Undo::ATOMIC, prevcur.pit());
1734                 mergeParagraph(bufparams, plist, prevcur.pit());
1735                 needsUpdate = true;
1736         }
1737
1738         if (needsUpdate) {
1739                 updateLabels(cur.buffer());
1740                 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1741         }
1742
1743         return needsUpdate;
1744 }
1745
1746
1747
1748
1749 bool LyXText::backspace(LCursor & cur)
1750 {
1751         BOOST_ASSERT(this == cur.text());
1752         bool needsUpdate = false;
1753         if (cur.pos() == 0) {
1754                 if (cur.pit() == 0)
1755                         return dissolveInset(cur);
1756
1757                 if (cur.buffer().params().trackChanges) {
1758                         // FIXME: Change tracking (MG)
1759                         // Previous paragraph, mark "carriage return" as
1760                         // deleted:
1761                         Paragraph & par = pars_[cur.pit() - 1];
1762                         // Take care of a just inserted para break:
1763                         // FIXME: change tracking (MG)
1764                         if (!par.isInserted(par.size())) {
1765                                 // FIXME: change tracking (MG)
1766                                 par.setChange(par.size(), Change(Change::DELETED));
1767                                 setCursorIntern(cur, cur.pit() - 1, par.size());
1768                                 return true;
1769                         }
1770                 }
1771
1772                 // The cursor is at the beginning of a paragraph, so
1773                 // the backspace will collapse two paragraphs into one.
1774                 needsUpdate = backspacePos0(cur);
1775
1776         } else {
1777                 // this is the code for a normal backspace, not pasting
1778                 // any paragraphs
1779                 recordUndo(cur, Undo::DELETE);
1780                 // We used to do cursorLeftIntern() here, but it is
1781                 // not a good idea since it triggers the auto-delete
1782                 // mechanism. So we do a cursorLeftIntern()-lite,
1783                 // without the dreaded mechanism. (JMarc)
1784                 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1785                                 false, cur.boundary());
1786                 // FIXME: change tracking (MG)
1787                 cur.paragraph().eraseChar(cur.pos(), cur.buffer().params().trackChanges);
1788         }
1789
1790         if (cur.pos() == cur.lastpos())
1791                 setCurrentFont(cur);
1792
1793         // FIXME: Backspacing has nothing to do with setting a cursor.
1794         // Because of the mix between the model (the paragraph contents)
1795         // and the view (the paragraph breaking in rows, we have to do this
1796         // here before the setCursor() call.
1797         if (redoParagraph(cur.bv(), cur.pit()))
1798                 // A singlePar update is not enough in this case.
1799                 cur.updateFlags(Update::Force);
1800         setCursor(cur, cur.pit(), cur.pos(), false, cur.boundary());
1801
1802         return needsUpdate;
1803 }
1804
1805
1806 bool LyXText::dissolveInset(LCursor & cur) {
1807         BOOST_ASSERT(this == cur.text());
1808
1809         if (isMainText(*cur.bv().buffer()) || cur.inset().nargs() != 1)
1810                 return false;
1811
1812         bool const in_ert = cur.inset().lyxCode() == InsetBase::ERT_CODE;
1813         recordUndoInset(cur);
1814         cur.selHandle(false);
1815         // save position
1816         pos_type spos = cur.pos();
1817         pit_type spit = cur.pit();
1818         ParagraphList plist;
1819         if (cur.lastpit() != 0 || cur.lastpos() != 0)
1820                 plist = paragraphs();
1821         cur.popLeft();
1822         // store cursor offset
1823         if (spit == 0)
1824                 spos += cur.pos();
1825         spit += cur.pit();
1826         Buffer & b = cur.buffer();
1827         // FIXME: change tracking (MG)
1828         cur.paragraph().eraseChar(cur.pos(), b.params().trackChanges);
1829         if (!plist.empty()) {
1830                 if (in_ert) {
1831                         // ERT paragraphs have the Language latex_language.
1832                         // This is invalid outside of ERT, so we need to
1833                         // change it to the buffer language.
1834                         ParagraphList::iterator it = plist.begin();
1835                         ParagraphList::iterator it_end = plist.end();
1836                         for (; it != it_end; it++) {
1837                                 it->changeLanguage(b.params(),
1838                                                 latex_language,
1839                                                 b.getLanguage());
1840                         }
1841                 }
1842
1843                 pasteParagraphList(cur, plist, b.params().textclass,
1844                                    b.errorList("Paste"));
1845                 // restore position
1846                 cur.pit() = std::min(cur.lastpit(), spit);
1847                 cur.pos() = std::min(cur.lastpos(), spos);
1848         }
1849         cur.clearSelection();
1850         cur.resetAnchor();
1851         return true;
1852 }
1853
1854
1855 Row const & LyXText::firstRow() const
1856 {
1857         return *paragraphs().front().rows().begin();
1858 }
1859
1860
1861 bool LyXText::redoParagraph(BufferView & bv, pit_type const pit)
1862 {
1863         // remove rows of paragraph, keep track of height changes
1864         Paragraph & par = pars_[pit];
1865         Buffer const & buffer = *bv.buffer();
1866
1867         // Add bibitem insets if necessary
1868         if (par.layout()->labeltype == LABEL_BIBLIO) {
1869                 bool hasbibitem(false);
1870                 if (!par.insetlist.empty()
1871                         // Insist on it being in pos 0
1872                         && par.getChar(0) == Paragraph::META_INSET) {
1873                         InsetBase * inset = par.insetlist.begin()->inset;
1874                         if (inset->lyxCode() == InsetBase::BIBITEM_CODE)
1875                                 hasbibitem = true;
1876                 }
1877                 if (!hasbibitem) {
1878                         InsetBibitem * inset(new
1879                                 InsetBibitem(InsetCommandParams("bibitem")));
1880                         par.insertInset(0, static_cast<InsetBase *>(inset),
1881                                         Change(buffer.params().trackChanges ?
1882                                                Change::INSERTED : Change::UNCHANGED));
1883                         bv.cursor().posRight();
1884                 }
1885         }
1886
1887         // Optimisation: this is used in the next two loops
1888         // so better to calculate that once here.
1889         int right_margin = rightMargin(buffer, par);
1890
1891         // redo insets
1892         // FIXME: We should always use getFont(), see documentation of
1893         // noFontChange() in insetbase.h.
1894         LyXFont const bufferfont = buffer.params().getFont();
1895         InsetList::iterator ii = par.insetlist.begin();
1896         InsetList::iterator iend = par.insetlist.end();
1897         for (; ii != iend; ++ii) {
1898                 Dimension dim;
1899                 int const w = maxwidth_ - leftMargin(buffer, pit, ii->pos)
1900                         - right_margin;
1901                 LyXFont const & font = ii->inset->noFontChange() ?
1902                         bufferfont :
1903                         getFont(buffer, par, ii->pos);
1904                 MetricsInfo mi(&bv, font, w);
1905                 ii->inset->metrics(mi, dim);
1906         }
1907
1908         // rebreak the paragraph
1909         par.rows().clear();
1910         Dimension dim;
1911
1912         par.setBeginOfBody();
1913         pos_type z = 0;
1914         do {
1915                 Row row(z);
1916                 rowBreakPoint(buffer, right_margin, pit, row);
1917                 setRowWidth(buffer, pit, row);
1918                 setHeightOfRow(bv, pit, row);
1919                 par.rows().push_back(row);
1920                 dim.wid = std::max(dim.wid, row.width());
1921                 dim.des += row.height();
1922                 z = row.endpos();
1923         } while (z < par.size());
1924
1925         // Make sure that if a par ends in newline, there is one more row
1926         // under it
1927         // FIXME this is a dirty trick. Now the _same_ position in the
1928         // paragraph occurs in _two_ different rows, and has two different
1929         // display positions, leading to weird behaviour when moving up/down.
1930         if (z > 0 && par.isNewline(z - 1)) {
1931                 Row row(z - 1);
1932                 row.endpos(z - 1);
1933                 setRowWidth(buffer, pit, row);
1934                 setHeightOfRow(bv, pit, row);
1935                 par.rows().push_back(row);
1936                 dim.des += row.height();
1937         }
1938
1939         dim.asc += par.rows()[0].ascent();
1940         dim.des -= par.rows()[0].ascent();
1941
1942         bool const same = dim.height() == par.dim().height();
1943
1944         par.dim() = dim;
1945         //lyxerr << "redoParagraph: " << par.rows().size() << " rows\n";
1946
1947         return !same;
1948 }
1949
1950
1951 void LyXText::metrics(MetricsInfo & mi, Dimension & dim)
1952 {
1953         //BOOST_ASSERT(mi.base.textwidth);
1954         if (mi.base.textwidth)
1955                 maxwidth_ = mi.base.textwidth;
1956         //lyxerr << "LyXText::metrics: width: " << mi.base.textwidth
1957         //      << " maxWidth: " << maxwidth_ << "\nfont: " << mi.base.font << endl;
1958         // save the caller's font locally:
1959         font_ = mi.base.font;
1960
1961         unsigned int h = 0;
1962         unsigned int w = 0;
1963         for (pit_type pit = 0, n = paragraphs().size(); pit != n; ++pit) {
1964                 redoParagraph(*mi.base.bv, pit);
1965                 Paragraph & par = paragraphs()[pit];
1966                 h += par.height();
1967                 if (w < par.width())
1968                         w = par.width();
1969         }
1970
1971         dim.wid = w;
1972         dim.asc = pars_[0].ascent();
1973         dim.des = h - dim.asc;
1974
1975         dim_ = dim;
1976 }
1977
1978
1979 // only used for inset right now. should also be used for main text
1980 void LyXText::draw(PainterInfo & pi, int x, int y) const
1981 {
1982         paintTextInset(*this, pi, x, y);
1983 }
1984
1985
1986 // only used for inset right now. should also be used for main text
1987 void LyXText::drawSelection(PainterInfo & pi, int x, int) const
1988 {
1989         LCursor & cur = pi.base.bv->cursor();
1990         if (!cur.selection())
1991                 return;
1992         if (!ptr_cmp(cur.text(), this))
1993                 return;
1994
1995         if (lyxerr.debugging(Debug::DEBUG)) {
1996                 lyxerr[Debug::DEBUG]
1997                         << BOOST_CURRENT_FUNCTION
1998                         << "draw selection at " << x
1999                         << endl;
2000         }
2001
2002         DocIterator beg = cur.selectionBegin();
2003         DocIterator end = cur.selectionEnd();
2004
2005         BufferView & bv = *pi.base.bv;
2006         Buffer const & buffer = *bv.buffer();
2007
2008         // the selection doesn't touch the visible screen
2009         if (bv_funcs::status(&bv, beg) == bv_funcs::CUR_BELOW
2010             || bv_funcs::status(&bv, end) == bv_funcs::CUR_ABOVE)
2011                 return;
2012
2013         Paragraph const & par1 = pars_[beg.pit()];
2014         Paragraph const & par2 = pars_[end.pit()];
2015
2016         bool const above = (bv_funcs::status(&bv, beg)
2017                             == bv_funcs::CUR_ABOVE);
2018         bool const below = (bv_funcs::status(&bv, end)
2019                             == bv_funcs::CUR_BELOW);
2020         int y1,y2,x1,x2;
2021         if (above) {
2022                 y1 = 0;
2023                 y2 = 0;
2024                 x1 = 0;
2025                 x2 = dim_.wid;
2026         } else {
2027                 Row const & row1 = par1.getRow(beg.pos(), beg.boundary());
2028                 y1 = bv_funcs::getPos(bv, beg, beg.boundary()).y_ - row1.ascent();
2029                 y2 = y1 + row1.height();
2030                 int const startx = cursorX(buffer, beg.top(), beg.boundary());
2031                 if (!isRTL(buffer, par1)) {
2032                         x1 = startx;
2033                         x2 = 0 + dim_.wid;
2034                 }
2035                 else {
2036                         x1 = 0;
2037                         x2 = startx;
2038                 }
2039         }
2040
2041         int Y1,Y2,X1,X2;
2042         if (below) {
2043                 Y1 = bv.workHeight();
2044                 Y2 = bv.workHeight();
2045                 X1 = 0;
2046                 X2 = dim_.wid;
2047         } else {
2048                 Row const & row2 = par2.getRow(end.pos(), end.boundary());
2049                 Y1 = bv_funcs::getPos(bv, end, end.boundary()).y_ - row2.ascent();
2050                 Y2 = Y1 + row2.height();
2051                 int const endx = cursorX(buffer, end.top(), end.boundary());
2052                 if (!isRTL(buffer, par2)) {
2053                         X1 = 0;
2054                         X2 = endx;
2055                 }
2056                 else {
2057                         X1 = endx;
2058                         X2 = 0 + dim_.wid;
2059                 }
2060         }
2061
2062         if (!above && !below && &par1.getRow(beg.pos(), beg.boundary())
2063             == &par2.getRow(end.pos(), end.boundary()))
2064         {
2065                 // paint only one rectangle
2066                 int const b( !isRTL(*bv.buffer(), par1) ? x + x1 : x + X1 );
2067                 int const w( !isRTL(*bv.buffer(), par1) ? X2 - x1 : x2 - X1 );
2068                 pi.pain.fillRectangle(b, y1, w, y2 - y1, LColor::selection);
2069                 return;
2070         }
2071
2072         if (lyxerr.debugging(Debug::DEBUG)) {
2073                 lyxerr[Debug::DEBUG] << " y1: " << y1 << " y2: " << y2
2074                            << "X1:" << X1 << " x2: " << X2 << " wid: " << dim_.wid
2075                         << endl;
2076         }
2077
2078         // paint upper rectangle
2079         pi.pain.fillRectangle(x + x1, y1, x2 - x1, y2 - y1,
2080                                       LColor::selection);
2081         // paint bottom rectangle
2082         pi.pain.fillRectangle(x + X1, Y1, X2 - X1, Y2 - Y1,
2083                                       LColor::selection);
2084         // paint center rectangle
2085         pi.pain.fillRectangle(x, y2, dim_.wid,
2086                               Y1 - y2, LColor::selection);
2087 }
2088
2089 bool LyXText::isLastRow(pit_type pit, Row const & row) const
2090 {
2091         return row.endpos() >= pars_[pit].size()
2092                 && pit + 1 == pit_type(paragraphs().size());
2093 }
2094
2095
2096 bool LyXText::isFirstRow(pit_type pit, Row const & row) const
2097 {
2098         return row.pos() == 0 && pit == 0;
2099 }
2100
2101
2102 void LyXText::getWord(CursorSlice & from, CursorSlice & to,
2103         word_location const loc)
2104 {
2105         Paragraph const & from_par = pars_[from.pit()];
2106         switch (loc) {
2107         case WHOLE_WORD_STRICT:
2108                 if (from.pos() == 0 || from.pos() == from_par.size()
2109                     || !from_par.isLetter(from.pos())
2110                     || !from_par.isLetter(from.pos() - 1)) {
2111                         to = from;
2112                         return;
2113                 }
2114                 // no break here, we go to the next
2115
2116         case WHOLE_WORD:
2117                 // If we are already at the beginning of a word, do nothing
2118                 if (!from.pos() || !from_par.isLetter(from.pos() - 1))
2119                         break;
2120                 // no break here, we go to the next
2121
2122         case PREVIOUS_WORD:
2123                 // always move the cursor to the beginning of previous word
2124                 while (from.pos() && from_par.isLetter(from.pos() - 1))
2125                         --from.pos();
2126                 break;
2127         case NEXT_WORD:
2128                 lyxerr << "LyXText::getWord: NEXT_WORD not implemented yet"
2129                        << endl;
2130                 break;
2131         case PARTIAL_WORD:
2132                 // no need to move the 'from' cursor
2133                 break;
2134         }
2135         to = from;
2136         Paragraph & to_par = pars_[to.pit()];
2137         while (to.pos() < to_par.size() && to_par.isLetter(to.pos()))
2138                 ++to.pos();
2139 }
2140
2141
2142 void LyXText::write(Buffer const & buf, std::ostream & os) const
2143 {
2144         ParagraphList::const_iterator pit = paragraphs().begin();
2145         ParagraphList::const_iterator end = paragraphs().end();
2146         depth_type dth = 0;
2147         for (; pit != end; ++pit)
2148                 pit->write(buf, os, buf.params(), dth);
2149 }
2150
2151
2152 bool LyXText::read(Buffer const & buf, LyXLex & lex, ErrorList & errorList)
2153 {
2154         depth_type depth = 0;
2155
2156         while (lex.isOK()) {
2157                 lex.nextToken();
2158                 string const token = lex.getString();
2159
2160                 if (token.empty())
2161                         continue;
2162
2163                 if (token == "\\end_inset")
2164                         break;
2165
2166                 if (token == "\\end_body")
2167                         continue;
2168
2169                 if (token == "\\begin_body")
2170                         continue;
2171
2172                 if (token == "\\end_document")
2173                         return false;
2174
2175                 if (token == "\\begin_layout") {
2176                         lex.pushToken(token);
2177
2178                         Paragraph par;
2179                         par.params().depth(depth);
2180                         par.setFont(0, LyXFont(LyXFont::ALL_INHERIT, buf.params().language));
2181                         pars_.push_back(par);
2182
2183                         // FIXME: goddamn InsetTabular makes us pass a Buffer
2184                         // not BufferParams
2185                         lyx::readParagraph(buf, pars_.back(), lex, errorList);
2186
2187                 } else if (token == "\\begin_deeper") {
2188                         ++depth;
2189                 } else if (token == "\\end_deeper") {
2190                         if (!depth) {
2191                                 lex.printError("\\end_deeper: " "depth is already null");
2192                         } else {
2193                                 --depth;
2194                         }
2195                 } else {
2196                         lyxerr << "Handling unknown body token: `"
2197                                << token << '\'' << endl;
2198                 }
2199         }
2200         return true;
2201 }
2202
2203
2204 int LyXText::ascent() const
2205 {
2206         return dim_.asc;
2207 }
2208
2209
2210 int LyXText::descent() const
2211 {
2212         return dim_.des;
2213 }
2214
2215
2216 int LyXText::cursorX(Buffer const & buffer, CursorSlice const & sl,
2217                 bool boundary) const
2218 {
2219         pit_type const pit = sl.pit();
2220         Paragraph const & par = pars_[pit];
2221         if (par.rows().empty())
2222                 return 0;
2223
2224         pos_type ppos = sl.pos();
2225         // Correct position in front of big insets
2226         bool const boundary_correction = ppos != 0 && boundary;
2227         if (boundary_correction)
2228                 --ppos;
2229
2230         Row const & row = par.getRow(sl.pos(), boundary);
2231
2232         pos_type cursor_vpos = 0;
2233
2234         RowMetrics const m = computeRowMetrics(buffer, pit, row);
2235         double x = m.x;
2236
2237         pos_type const row_pos  = row.pos();
2238         pos_type const end      = row.endpos();
2239
2240         if (end <= row_pos)
2241                 cursor_vpos = row_pos;
2242         else if (ppos >= end)
2243                 cursor_vpos = isRTL(buffer, par) ? row_pos : end;
2244         else if (ppos > row_pos && ppos >= end)
2245                 // Place cursor after char at (logical) position pos - 1
2246                 cursor_vpos = (bidi.level(ppos - 1) % 2 == 0)
2247                         ? bidi.log2vis(ppos - 1) + 1 : bidi.log2vis(ppos - 1);
2248         else
2249                 // Place cursor before char at (logical) position ppos
2250                 cursor_vpos = (bidi.level(ppos) % 2 == 0)
2251                         ? bidi.log2vis(ppos) : bidi.log2vis(ppos) + 1;
2252
2253         pos_type body_pos = par.beginOfBody();
2254         if (body_pos > 0 &&
2255             (body_pos > end || !par.isLineSeparator(body_pos - 1)))
2256                 body_pos = 0;
2257
2258         // Use font span to speed things up, see below
2259         FontSpan font_span;
2260         LyXFont font;
2261         FontMetrics const & labelfm = theFontMetrics(
2262                 getLabelFont(buffer, par));
2263
2264         for (pos_type vpos = row_pos; vpos < cursor_vpos; ++vpos) {
2265                 pos_type pos = bidi.vis2log(vpos);
2266                 if (body_pos > 0 && pos == body_pos - 1) {
2267                         // FIXME UNICODE
2268                         docstring const lsep = from_utf8(par.layout()->labelsep);
2269                         x += m.label_hfill + labelfm.width(lsep);
2270                         if (par.isLineSeparator(body_pos - 1))
2271                                 x -= singleWidth(buffer, par, body_pos - 1);
2272                 }
2273
2274                 // Use font span to speed things up, see above
2275                 if (pos < font_span.first || pos > font_span.last) {
2276                         font_span = par.fontSpan(pos);
2277                         font = getFont(buffer, par, pos);
2278                 }
2279
2280                 x += singleWidth(par, pos, par.getChar(pos), font);
2281
2282                 if (par.hfillExpansion(row, pos))
2283                         x += (pos >= body_pos) ? m.hfill : m.label_hfill;
2284                 else if (par.isSeparator(pos) && pos >= body_pos)
2285                         x += m.separator;
2286         }
2287
2288         // see correction above
2289         if (boundary_correction)
2290                 if (getFont(buffer, par, ppos).isVisibleRightToLeft())
2291                         x -= singleWidth(buffer, par, ppos);
2292                 else
2293                         x += singleWidth(buffer, par, ppos);
2294
2295         // Make sure inside an inset we always count from the left
2296         // edge (bidi!) -- MV
2297         if (sl.pos() < par.size()) {
2298                 font = getFont(buffer, par, sl.pos());
2299                 if (!boundary && font.isVisibleRightToLeft()
2300                   && par.isInset(sl.pos()))
2301                         x -= par.getInset(sl.pos())->width();
2302         }
2303         return int(x);
2304 }
2305
2306
2307 int LyXText::cursorY(CursorSlice const & sl, bool boundary) const
2308 {
2309         //lyxerr << "LyXText::cursorY: boundary: " << boundary << std::endl;
2310         Paragraph const & par = getPar(sl.pit());
2311         if (par.rows().empty())
2312                 return 0;
2313
2314         int h = 0;
2315         h -= pars_[0].rows()[0].ascent();
2316         for (pit_type pit = 0; pit < sl.pit(); ++pit)
2317                 h += pars_[pit].height();
2318         int pos = sl.pos();
2319         if (pos && boundary)
2320                 --pos;
2321         size_t const rend = par.pos2row(pos);
2322         for (size_t rit = 0; rit != rend; ++rit)
2323                 h += par.rows()[rit].height();
2324         h += par.rows()[rend].ascent();
2325         return h;
2326 }
2327
2328
2329 // Returns the current font and depth as a message.
2330 string LyXText::currentState(LCursor & cur)
2331 {
2332         BOOST_ASSERT(this == cur.text());
2333         Buffer & buf = cur.buffer();
2334         Paragraph const & par = cur.paragraph();
2335         std::ostringstream os;
2336
2337         if (buf.params().trackChanges)
2338                 os << "[C] ";
2339
2340         Change change = par.lookupChange(cur.pos());
2341
2342         if (change.type != Change::UNCHANGED) {
2343                 Author const & a = buf.params().authors().get(change.author);
2344                 os << to_utf8(_("Change: ")) << a.name();
2345                 if (!a.email().empty())
2346                         os << " (" << a.email() << ")";
2347                 os << to_utf8(_(" at ")) << ctime(&change.changetime);
2348                 os << " : ";
2349         }
2350
2351         // I think we should only show changes from the default
2352         // font. (Asger)
2353         // No, from the document font (MV)
2354         LyXFont font = real_current_font;
2355         font.reduce(buf.params().getFont());
2356
2357         // avoid to_utf8(_(...)) re-entrance problem
2358         string const s = font.stateText(&buf.params());
2359         os << to_utf8(bformat(_("Font: %1$s"), from_utf8(s)));
2360
2361         // os << to_utf8(bformat(_("Font: %1$s"), font.stateText(&buf.params)));
2362
2363         // The paragraph depth
2364         int depth = cur.paragraph().getDepth();
2365         if (depth > 0)
2366                 os << to_utf8(bformat(_(", Depth: %1$d"), depth));
2367
2368         // The paragraph spacing, but only if different from
2369         // buffer spacing.
2370         Spacing const & spacing = par.params().spacing();
2371         if (!spacing.isDefault()) {
2372                 os << to_utf8(_(", Spacing: "));
2373                 switch (spacing.getSpace()) {
2374                 case Spacing::Single:
2375                         os << to_utf8(_("Single"));
2376                         break;
2377                 case Spacing::Onehalf:
2378                         os << to_utf8(_("OneHalf"));
2379                         break;
2380                 case Spacing::Double:
2381                         os << to_utf8(_("Double"));
2382                         break;
2383                 case Spacing::Other:
2384                         os << to_utf8(_("Other (")) << spacing.getValueAsString() << ')';
2385                         break;
2386                 case Spacing::Default:
2387                         // should never happen, do nothing
2388                         break;
2389                 }
2390         }
2391
2392 #ifdef DEVEL_VERSION
2393         os << to_utf8(_(", Inset: ")) << &cur.inset();
2394         os << to_utf8(_(", Paragraph: ")) << cur.pit();
2395         os << to_utf8(_(", Id: ")) << par.id();
2396         os << to_utf8(_(", Position: ")) << cur.pos();
2397         os << to_utf8(_(", Boundary: ")) << cur.boundary();
2398 //      Row & row = cur.textRow();
2399 //      os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
2400 #endif
2401         return os.str();
2402 }
2403
2404
2405 docstring LyXText::getPossibleLabel(LCursor & cur) const
2406 {
2407         pit_type pit = cur.pit();
2408
2409         LyXLayout_ptr layout = pars_[pit].layout();
2410
2411         if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
2412                 LyXLayout_ptr const & layout2 = pars_[pit - 1].layout();
2413                 if (layout2->latextype != LATEX_PARAGRAPH) {
2414                         --pit;
2415                         layout = layout2;
2416                 }
2417         }
2418
2419         docstring name = from_ascii(layout->latexname());
2420
2421         // for captions, we want the abbreviation of the float type
2422         if (layout->labeltype == LABEL_SENSITIVE) {
2423                 // Search for the first float or wrap inset in the iterator
2424                 for (int i = cur.depth(); --i >= 0; ) {
2425                         InsetBase * const in = &cur[i].inset();
2426                         if (in->lyxCode() == InsetBase::FLOAT_CODE
2427                             || in->lyxCode() == InsetBase::WRAP_CODE) {
2428                                 name = in->getInsetName();
2429                                 break;
2430                         }
2431                 }
2432         }
2433
2434         docstring text = name.substr(0, 3);
2435         if (name == "theorem")
2436                 text = from_ascii("thm"); // Create a correct prefix for prettyref
2437
2438         text += ':';
2439         if (layout->latextype == LATEX_PARAGRAPH || lyxrc.label_init_length < 0)
2440                 text.erase();
2441
2442         docstring par_text = pars_[pit].asString(cur.buffer(), false);
2443         for (int i = 0; i < lyxrc.label_init_length; ++i) {
2444                 if (par_text.empty())
2445                         break;
2446                 docstring head;
2447                 par_text = split(par_text, head, ' ');
2448                 // Is it legal to use spaces in labels ?
2449                 if (i > 0)
2450                         text += '-';
2451                 text += head;
2452         }
2453
2454         return text;
2455 }
2456
2457
2458 //pos_type LyXText::x2pos(pit_type pit, int row, int x) const
2459 //{
2460 //      int lastx = 0;
2461 //      int currx = 0;
2462 //      Paragraph const & par = pars_[pit];
2463 //      Row const & r = par.rows()[row];
2464 //      int pos = r.pos();
2465 //      for (; currx < x && pos < r.endpos(); ++pos) {
2466 //              lastx = currx;
2467 //              currx += singleWidth(buffer, par, pos);
2468 //      }
2469 //      if (abs(lastx - x) < abs(currx - x) && pos != r.pos())
2470 //              --pos;
2471 //      return pos;
2472 //}
2473
2474
2475 pos_type LyXText::x2pos(BufferView const & bv, pit_type pit, int row,
2476                 int x) const
2477 {
2478         BOOST_ASSERT(row < int(pars_[pit].rows().size()));
2479         bool bound = false;
2480         Row const & r = pars_[pit].rows()[row];
2481         return r.pos() + getColumnNearX(bv, pit, r, x, bound);
2482 }
2483
2484
2485 //int LyXText::pos2x(pit_type pit, pos_type pos) const
2486 //{
2487 //      Paragraph const & par = pars_[pit];
2488 //      Row const & r = par.rows()[row];
2489 //      int x = 0;
2490 //      pos -= r.pos();
2491 //}
2492
2493
2494 // x,y are screen coordinates
2495 // sets cursor only within this LyXText
2496 bool LyXText::setCursorFromCoordinates(LCursor & cur, int const x, int const y)
2497 {
2498         BOOST_ASSERT(this == cur.text());
2499         pit_type pit = getPitNearY(cur.bv(), y);
2500         int yy = cur.bv().coordCache().get(this, pit).y_ - pars_[pit].ascent();
2501         lyxerr[Debug::DEBUG]
2502                 << BOOST_CURRENT_FUNCTION
2503                 << ": x: " << x
2504                 << " y: " << y
2505                 << " pit: " << pit
2506                 << " yy: " << yy << endl;
2507
2508         Paragraph const & par = pars_[pit];
2509         int r = 0;
2510         BOOST_ASSERT(par.rows().size());
2511         for (; r < int(par.rows().size()) - 1; ++r) {
2512                 Row const & row = par.rows()[r];
2513                 if (int(yy + row.height()) > y)
2514                         break;
2515                 yy += row.height();
2516         }
2517
2518         Row const & row = par.rows()[r];
2519
2520         lyxerr[Debug::DEBUG]
2521                 << BOOST_CURRENT_FUNCTION
2522                 << ": row " << r
2523                 << " from pos: " << row.pos()
2524                 << endl;
2525
2526         bool bound = false;
2527         int xx = x;
2528         pos_type const pos = row.pos() + getColumnNearX(cur.bv(), pit, row,
2529                 xx, bound);
2530
2531         lyxerr[Debug::DEBUG]
2532                 << BOOST_CURRENT_FUNCTION
2533                 << ": setting cursor pit: " << pit
2534                 << " pos: " << pos
2535                 << endl;
2536
2537         return setCursor(cur, pit, pos, true, bound);
2538 }
2539
2540
2541 void LyXText::charsTranspose(LCursor & cur)
2542 {
2543         BOOST_ASSERT(this == cur.text());
2544
2545         pos_type pos = cur.pos();
2546
2547         // If cursor is at beginning or end of paragraph, do nothing.
2548         if (pos == cur.lastpos() || pos == 0)
2549                 return;
2550
2551         Paragraph & par = cur.paragraph();
2552
2553         // Get the positions of the characters to be transposed. 
2554         pos_type pos1 = pos - 1;
2555         pos_type pos2 = pos;
2556
2557         // In change tracking mode, ignore deleted characters.
2558         while (pos2 < cur.lastpos() && par.isDeleted(pos2))
2559                 ++pos2;
2560         if (pos2 == cur.lastpos())
2561                 return;
2562
2563         while (pos1 >= 0 && par.isDeleted(pos1))
2564                 --pos1;
2565         if (pos1 < 0)
2566                 return;
2567
2568         // Don't do anything if one of the "characters" is not regular text.
2569         if (par.isInset(pos1) || par.isInset(pos2))
2570                 return;
2571
2572         // Store the characters to be transposed (including font information).
2573         char_type char1 = par.getChar(pos1);
2574         LyXFont const font1 =
2575                 par.getFontSettings(cur.buffer().params(), pos1);
2576         
2577         char_type char2 = par.getChar(pos2);
2578         LyXFont const font2 =
2579                 par.getFontSettings(cur.buffer().params(), pos2);
2580
2581         // And finally, we are ready to perform the transposition.
2582         // Track the changes if Change Tracking is enabled.
2583         bool const trackChanges = cur.buffer().params().trackChanges;
2584
2585         recordUndo(cur);
2586
2587         par.eraseChar(pos2, trackChanges);
2588         par.eraseChar(pos1, trackChanges);
2589         par.insertChar(pos1, char2, font2, trackChanges);
2590         par.insertChar(pos2, char1, font1, trackChanges);
2591
2592         // After the transposition, move cursor to after the transposition.
2593         setCursor(cur, cur.pit(), pos2);
2594         cur.forwardPos();
2595 }
2596
2597
2598 } // namespace lyx