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