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