]> git.lyx.org Git - lyx.git/blob - src/text.C
b6d69c991b27939d7f9549c40a4644036dd1ad8b
[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.erase(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].erase(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 #ifdef WITH_WARNINGS
1628 #warning changes
1629 #endif
1630                 pars_[pit].setChar(pos, c);
1631                 ++pos;
1632         }
1633 }
1634
1635
1636 bool LyXText::erase(LCursor & cur)
1637 {
1638         BOOST_ASSERT(this == cur.text());
1639         bool needsUpdate = false;
1640
1641         if (cur.pos() != cur.lastpos()) {
1642                 recordUndo(cur, Undo::DELETE, cur.pit());
1643                 setCursorIntern(cur, cur.pit(), cur.pos() + 1, false, cur.boundary());
1644                 needsUpdate = backspace(cur);
1645                 // FIXME: change tracking (MG)
1646                 if (cur.paragraph().lookupChange(cur.pos()) == Change(Change::DELETED))
1647                         cur.posRight();
1648         } else if (cur.pit() != cur.lastpit()) {
1649                 LCursor scur = cur;
1650
1651                 setCursorIntern(cur, cur.pit() + 1, 0, false, false);
1652                 if (pars_[cur.pit()].layout() == pars_[scur.pit()].layout()) {
1653                         recordUndo(scur, Undo::DELETE, scur.pit());
1654                         needsUpdate = backspace(cur);
1655                         if (cur.buffer().params().trackChanges) {
1656                                 // FIXME: Change tracking (MG)
1657                                 // move forward after the paragraph break is DELETED
1658                                 Paragraph & par = cur.paragraph();
1659                                 // FIXME: change tracking (MG)
1660                                 if (par.lookupChange(par.size()) == Change(Change::DELETED))
1661                                         setCursorIntern(cur, cur.pit() + 1, 0);
1662                                 }
1663                 } else {
1664                         setCursorIntern(scur, scur.pit(), scur.pos(), false, scur.boundary());
1665                 }
1666         } else
1667                 needsUpdate = dissolveInset(cur);
1668
1669         return needsUpdate;
1670 }
1671
1672
1673 bool LyXText::backspacePos0(LCursor & cur)
1674 {
1675         BOOST_ASSERT(this == cur.text());
1676         bool needsUpdate = false;
1677
1678         Paragraph & par = cur.paragraph();
1679         // is it an empty paragraph?
1680         pos_type lastpos = cur.lastpos();
1681         if (lastpos == 0 || (lastpos == 1 && par.isSeparator(0))) {
1682                 // This is an empty paragraph and we delete it just
1683                 // by moving the cursor one step
1684                 // left and let the DeleteEmptyParagraphMechanism
1685                 // handle the actual deletion of the paragraph.
1686
1687                 if (cur.pit() != 0) {
1688                         // For KeepEmpty layouts we need to get
1689                         // rid of the keepEmpty setting first.
1690                         // And the only way to do this is to
1691                         // reset the layout to something
1692                         // else: f.ex. the default layout.
1693                         if (par.allowEmpty()) {
1694                                 Buffer & buf = cur.buffer();
1695                                 BufferParams const & bparams = buf.params();
1696                                 par.layout(bparams.getLyXTextClass().defaultLayout());
1697                         }
1698
1699                         cursorLeft(cur);
1700                         return true;
1701                 }
1702         }
1703
1704         if (cur.pit() != 0)
1705                 recordUndo(cur, Undo::DELETE, cur.pit() - 1);
1706
1707         pit_type tmppit = cur.pit();
1708         // We used to do cursorLeftIntern() here, but it is
1709         // not a good idea since it triggers the auto-delete
1710         // mechanism. So we do a cursorLeftIntern()-lite,
1711         // without the dreaded mechanism. (JMarc)
1712         if (cur.pit() != 0) {
1713                 // steps into the above paragraph.
1714                 setCursorIntern(cur, cur.pit() - 1,
1715                                 pars_[cur.pit() - 1].size(),
1716                                 false);
1717         }
1718
1719         // Pasting is not allowed, if the paragraphs have different
1720         // layout. I think it is a real bug of all other
1721         // word processors to allow it. It confuses the user.
1722         // Correction: Pasting is always allowed with standard-layout
1723         // Correction (Jug 20050717): Remove check about alignment!
1724         Buffer & buf = cur.buffer();
1725         BufferParams const & bufparams = buf.params();
1726         LyXTextClass const & tclass = bufparams.getLyXTextClass();
1727         pit_type const cpit = cur.pit();
1728
1729         if (cpit != tmppit
1730             && (pars_[cpit].layout() == pars_[tmppit].layout()
1731                 || pars_[tmppit].layout() == tclass.defaultLayout()))
1732         {
1733                 mergeParagraph(bufparams, pars_, cpit);
1734                 needsUpdate = true;
1735
1736                 if (cur.pos() != 0 && pars_[cpit].isSeparator(cur.pos() - 1))
1737                                 --cur.pos();
1738
1739                 // the counters may have changed
1740                 ParIterator par_it(cur);
1741                 updateLabels(cur.buffer(), par_it);
1742
1743                 setCursor(cur, cur.pit(), cur.pos(), false);
1744         }
1745         return needsUpdate;
1746 }
1747
1748
1749 bool LyXText::backspace(LCursor & cur)
1750 {
1751         BOOST_ASSERT(this == cur.text());
1752         bool needsUpdate = false;
1753         if (cur.pos() == 0) {
1754                 if (cur.pit() == 0)
1755                         return dissolveInset(cur);
1756
1757                 // The cursor is at the beginning of a paragraph, so
1758                 // the the backspace will collapse two paragraphs into
1759                 // one.
1760
1761                 if (cur.pit() != 0 && cur.buffer().params().trackChanges) {
1762                         // FIXME: Change tracking (MG)
1763                         // Previous paragraph, mark "carriage return" as
1764                         // deleted:
1765                         Paragraph & par = pars_[cur.pit() - 1];
1766                         // Take care of a just inserted para break:
1767                         // FIXME: change tracking (MG)
1768                         if (par.lookupChange(par.size()) != Change(Change::INSERTED)) {
1769                                 // FIXME: change tracking (MG)
1770                                 par.setChange(par.size(), Change(Change::DELETED));
1771                                 setCursorIntern(cur, cur.pit() - 1, par.size());
1772                                 return true;
1773                         }
1774                 }
1775
1776                 needsUpdate = backspacePos0(cur);
1777
1778         } else {
1779                 // this is the code for a normal backspace, not pasting
1780                 // any paragraphs
1781                 recordUndo(cur, Undo::DELETE);
1782                 // We used to do cursorLeftIntern() here, but it is
1783                 // not a good idea since it triggers the auto-delete
1784                 // mechanism. So we do a cursorLeftIntern()-lite,
1785                 // without the dreaded mechanism. (JMarc)
1786                 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1787                                 false, cur.boundary());
1788                 // FIXME: change tracking (MG)
1789                 cur.paragraph().erase(cur.pos(), cur.buffer().params().trackChanges);
1790         }
1791
1792         if (cur.pos() == cur.lastpos())
1793                 setCurrentFont(cur);
1794
1795         setCursor(cur, cur.pit(), cur.pos(), false, cur.boundary());
1796
1797         return needsUpdate;
1798 }
1799
1800
1801 bool LyXText::dissolveInset(LCursor & cur) {
1802         BOOST_ASSERT(this == cur.text());
1803
1804         if (isMainText() || cur.inset().nargs() != 1)
1805                 return false;
1806
1807         recordUndoInset(cur);
1808         cur.selHandle(false);
1809         // save position
1810         pos_type spos = cur.pos();
1811         pit_type spit = cur.pit();
1812         ParagraphList plist;
1813         if (cur.lastpit() != 0 || cur.lastpos() != 0)
1814                 plist = paragraphs();
1815         cur.popLeft();
1816         // store cursor offset
1817         if (spit == 0)
1818                 spos += cur.pos();
1819         spit += cur.pit();
1820         Buffer & b = cur.buffer();
1821         // FIXME: change tracking (MG)
1822         cur.paragraph().erase(cur.pos(), b.params().trackChanges);
1823         if (!plist.empty()) {
1824                 pasteParagraphList(cur, plist, b.params().textclass,
1825                                    b.errorList("Paste"));
1826                 // restore position
1827                 cur.pit() = std::min(cur.lastpit(), spit);
1828                 cur.pos() = std::min(cur.lastpos(), spos);
1829         }
1830         cur.clearSelection();
1831         cur.resetAnchor();
1832         return true;
1833 }
1834
1835
1836 Row const & LyXText::firstRow() const
1837 {
1838         return *paragraphs().front().rows().begin();
1839 }
1840
1841
1842 bool LyXText::redoParagraph(pit_type const pit)
1843 {
1844         // remove rows of paragraph, keep track of height changes
1845         Paragraph & par = pars_[pit];
1846
1847         // Add bibitem insets if necessary
1848         if (par.layout()->labeltype == LABEL_BIBLIO) {
1849                 bool hasbibitem(false);
1850                 if (!par.insetlist.empty()
1851                         // Insist on it being in pos 0
1852                         && par.getChar(0) == Paragraph::META_INSET) {
1853                         InsetBase * inset = par.insetlist.begin()->inset;
1854                         if (inset->lyxCode() == InsetBase::BIBITEM_CODE)
1855                                 hasbibitem = true;
1856                 }
1857                 if (!hasbibitem) {
1858                         InsetBibitem * inset(new
1859                                 InsetBibitem(InsetCommandParams("bibitem")));
1860                         // FIXME: change tracking (MG)
1861                         par.insertInset(0, static_cast<InsetBase *>(inset), Change(Change::INSERTED));
1862                         bv()->cursor().posRight();
1863                 }
1864         }
1865
1866         // redo insets
1867         // FIXME: We should always use getFont(), see documentation of
1868         // noFontChange() in insetbase.h.
1869         LyXFont const bufferfont = bv()->buffer()->params().getFont();
1870         InsetList::iterator ii = par.insetlist.begin();
1871         InsetList::iterator iend = par.insetlist.end();
1872         for (; ii != iend; ++ii) {
1873                 Dimension dim;
1874                 int const w = maxwidth_ - leftMargin(pit, ii->pos) - rightMargin(par);
1875                 LyXFont const & font = ii->inset->noFontChange() ?
1876                         bufferfont :
1877                         getFont(par, ii->pos);
1878                 MetricsInfo mi(bv(), font, w);
1879                 ii->inset->metrics(mi, dim);
1880         }
1881
1882         // rebreak the paragraph
1883         par.rows().clear();
1884         Dimension dim;
1885
1886         par.setBeginOfBody();
1887         pos_type z = 0;
1888         do {
1889                 Row row(z);
1890                 rowBreakPoint(pit, row);
1891                 setRowWidth(pit, row);
1892                 setHeightOfRow(pit, row);
1893                 par.rows().push_back(row);
1894                 dim.wid = std::max(dim.wid, row.width());
1895                 dim.des += row.height();
1896                 z = row.endpos();
1897         } while (z < par.size());
1898
1899         // Make sure that if a par ends in newline, there is one more row
1900         // under it
1901         // FIXME this is a dirty trick. Now the _same_ position in the
1902         // paragraph occurs in _two_ different rows, and has two different
1903         // display positions, leading to weird behaviour when moving up/down.
1904         if (z > 0 && par.isNewline(z - 1)) {
1905                 Row row(z - 1);
1906                 row.endpos(z - 1);
1907                 setRowWidth(pit, row);
1908                 setHeightOfRow(pit, row);
1909                 par.rows().push_back(row);
1910                 dim.des += row.height();
1911         }
1912
1913         dim.asc += par.rows()[0].ascent();
1914         dim.des -= par.rows()[0].ascent();
1915
1916         bool const same = dim == par.dim();
1917
1918         par.dim() = dim;
1919         //lyxerr << "redoParagraph: " << par.rows().size() << " rows\n";
1920
1921         return !same;
1922 }
1923
1924
1925 void LyXText::metrics(MetricsInfo & mi, Dimension & dim)
1926 {
1927         //BOOST_ASSERT(mi.base.textwidth);
1928         if (mi.base.textwidth)
1929                 maxwidth_ = mi.base.textwidth;
1930         //lyxerr << "LyXText::metrics: width: " << mi.base.textwidth
1931         //      << " maxWidth: " << maxwidth_ << "\nfont: " << mi.base.font << endl;
1932         // save the caller's font locally:
1933         font_ = mi.base.font;
1934
1935         unsigned int h = 0;
1936         unsigned int w = 0;
1937         for (pit_type pit = 0, n = paragraphs().size(); pit != n; ++pit) {
1938                 redoParagraph(pit);
1939                 Paragraph & par = paragraphs()[pit];
1940                 h += par.height();
1941                 if (w < par.width())
1942                         w = par.width();
1943         }
1944
1945         dim.wid = w;
1946         dim.asc = pars_[0].ascent();
1947         dim.des = h - dim.asc;
1948
1949         dim_ = dim;
1950 }
1951
1952
1953 // only used for inset right now. should also be used for main text
1954 void LyXText::draw(PainterInfo & pi, int x, int y) const
1955 {
1956         paintTextInset(*this, pi, x, y);
1957 }
1958
1959
1960 #if 0
1961 // only used for inset right now. should also be used for main text
1962 void LyXText::drawSelection(PainterInfo & pi, int x , int) const
1963 {
1964         LCursor & cur = pi.base.bv->cursor();
1965         if (!cur.selection())
1966                 return;
1967         if (!ptr_cmp(cur.text(), this))
1968                 return;
1969
1970         lyxerr << "draw selection at " << x << endl;
1971
1972         DocIterator beg = cur.selectionBegin();
1973         DocIterator end = cur.selectionEnd();
1974
1975         // the selection doesn't touch the visible screen
1976         if (bv_funcs::status(pi.base.bv, beg) == bv_funcs::CUR_BELOW
1977             || bv_funcs::status(pi.base.bv, end) == bv_funcs::CUR_ABOVE)
1978                 return;
1979
1980         Paragraph const & par1 = pars_[beg.pit()];
1981         Paragraph const & par2 = pars_[end.pit()];
1982
1983         Row const & row1 = par1.getRow(beg.pos(), beg.boundary());
1984         Row const & row2 = par2.getRow(end.pos(), end.boundary());
1985
1986         int y1,x1,x2;
1987         if (bv_funcs::status(pi.base.bv, beg) == bv_funcs::CUR_ABOVE) {
1988                 y1 = 0;
1989                 x1 = 0;
1990                 x2 = 0;
1991         } else {
1992                 y1 = bv_funcs::getPos(beg).y_ - row1.ascent();
1993                 int const startx = cursorX(beg.top(), begin.boundary());
1994                 x1 = isRTL(par1) ? startx : 0;
1995                 x2 = isRTL(par1) ? 0 + dim_.wid : startx;
1996         }
1997
1998         int y2,X1,X2;
1999         if (bv_funcs::status(pi.base.bv, end) == bv_funcs::CUR_BELOW) {
2000                 y2 = pi.base.bv->workHeight();
2001                 X1 = 0;
2002                 X2 = 0;
2003         } else {
2004                 y2 = bv_funcs::getPos(end).y_ + row2.descent();
2005                 int const endx = cursorX(end.top(), end.boundary());
2006                 X1 = isRTL(par2) ? 0 : endx;
2007                 X2 = isRTL(par2) ? endx : 0 + dim_.wid;
2008         }
2009
2010         lyxerr << " y1: " << y1 << " y2: " << y2
2011                 << " xo: " << xo_ << " wid: " << dim_.wid
2012                 << endl;
2013
2014         // paint big rectangle in one go
2015         pi.pain.fillRectangle(x, y1, dim_.wid, y2 - y1, LColor::selection);
2016
2017         // reset background at begin of first selected line
2018         pi.pain.fillRectangle(x + x1, y1, x2 - x1, row1.height(),
2019                 LColor::background);
2020
2021         // reset background at end of last selected line
2022         pi.pain.fillRectangle(x + X1, y2  - row2.height(),
2023                 X2 - X1, row2.height(), LColor::background);
2024 }
2025
2026 #else
2027
2028 void LyXText::drawSelection(PainterInfo & pi, int x, int) const
2029 {
2030         LCursor & cur = pi.base.bv->cursor();
2031         if (!cur.selection())
2032                 return;
2033         if (!ptr_cmp(cur.text(), this))
2034                 return;
2035
2036         lyxerr[Debug::DEBUG]
2037                 << BOOST_CURRENT_FUNCTION
2038                 << "draw selection at " << x
2039                 << endl;
2040
2041         DocIterator beg = cur.selectionBegin();
2042         DocIterator end = cur.selectionEnd();
2043
2044         BufferView * bv = pi.base.bv;
2045
2046         // the selection doesn't touch the visible screen
2047         if (bv_funcs::status(bv, beg) == bv_funcs::CUR_BELOW
2048             || bv_funcs::status(bv, end) == bv_funcs::CUR_ABOVE)
2049                 return;
2050
2051         Paragraph const & par1 = pars_[beg.pit()];
2052         Paragraph const & par2 = pars_[end.pit()];
2053
2054         bool const above = (bv_funcs::status(bv, beg)
2055                             == bv_funcs::CUR_ABOVE);
2056         bool const below = (bv_funcs::status(bv, end)
2057                             == bv_funcs::CUR_BELOW);
2058         int y1,y2,x1,x2;
2059         if (above) {
2060                 y1 = 0;
2061                 y2 = 0;
2062                 x1 = 0;
2063                 x2 = dim_.wid;
2064         } else {
2065                 Row const & row1 = par1.getRow(beg.pos(), beg.boundary());
2066                 y1 = bv_funcs::getPos(*bv, beg, beg.boundary()).y_ - row1.ascent();
2067                 y2 = y1 + row1.height();
2068                 int const startx = cursorX(beg.top(), beg.boundary());
2069                 x1 = !isRTL(par1) ? startx : 0;
2070                 x2 = !isRTL(par1) ? 0 + dim_.wid : startx;
2071         }
2072
2073         int Y1,Y2,X1,X2;
2074         if (below) {
2075                 Y1 = bv->workHeight();
2076                 Y2 = bv->workHeight();
2077                 X1 = 0;
2078                 X2 = dim_.wid;
2079         } else {
2080                 Row const & row2 = par2.getRow(end.pos(), end.boundary());
2081                 Y1 = bv_funcs::getPos(*bv, end, end.boundary()).y_ - row2.ascent();
2082                 Y2 = Y1 + row2.height();
2083                 int const endx = cursorX(end.top(), end.boundary());
2084                 X1 = !isRTL(par2) ? 0 : endx;
2085                 X2 = !isRTL(par2) ? endx : 0 + dim_.wid;
2086         }
2087
2088         if (!above && !below && &par1.getRow(beg.pos(), beg.boundary())
2089             == &par2.getRow(end.pos(), end.boundary()))
2090         {
2091                 // paint only one rectangle
2092                 int const b( !isRTL(par1) ? x + x1 : x + X1 );
2093                 int const w( !isRTL(par1) ? X2 - x1 : x2 - X1 );
2094                 pi.pain.fillRectangle(b, y1, w, y2 - y1, LColor::selection);
2095                 return;
2096         }
2097
2098         lyxerr[Debug::DEBUG] << " y1: " << y1 << " y2: " << y2
2099                << "X1:" << X1 << " x2: " << X2 << " wid: " << dim_.wid
2100                 << endl;
2101
2102         // paint upper rectangle
2103         pi.pain.fillRectangle(x + x1, y1, x2 - x1, y2 - y1,
2104                                       LColor::selection);
2105         // paint bottom rectangle
2106         pi.pain.fillRectangle(x + X1, Y1, X2 - X1, Y2 - Y1,
2107                                       LColor::selection);
2108         // paint center rectangle
2109         pi.pain.fillRectangle(x, y2, dim_.wid,
2110                               Y1 - y2, LColor::selection);
2111 }
2112 #endif
2113
2114 bool LyXText::isLastRow(pit_type pit, Row const & row) const
2115 {
2116         return row.endpos() >= pars_[pit].size()
2117                 && pit + 1 == pit_type(paragraphs().size());
2118 }
2119
2120
2121 bool LyXText::isFirstRow(pit_type pit, Row const & row) const
2122 {
2123         return row.pos() == 0 && pit == 0;
2124 }
2125
2126
2127 void LyXText::getWord(CursorSlice & from, CursorSlice & to,
2128         word_location const loc)
2129 {
2130         Paragraph const & from_par = pars_[from.pit()];
2131         switch (loc) {
2132         case WHOLE_WORD_STRICT:
2133                 if (from.pos() == 0 || from.pos() == from_par.size()
2134                     || !from_par.isLetter(from.pos())
2135                     || !from_par.isLetter(from.pos() - 1)) {
2136                         to = from;
2137                         return;
2138                 }
2139                 // no break here, we go to the next
2140
2141         case WHOLE_WORD:
2142                 // If we are already at the beginning of a word, do nothing
2143                 if (!from.pos() || !from_par.isLetter(from.pos() - 1))
2144                         break;
2145                 // no break here, we go to the next
2146
2147         case PREVIOUS_WORD:
2148                 // always move the cursor to the beginning of previous word
2149                 while (from.pos() && from_par.isLetter(from.pos() - 1))
2150                         --from.pos();
2151                 break;
2152         case NEXT_WORD:
2153                 lyxerr << "LyXText::getWord: NEXT_WORD not implemented yet"
2154                        << endl;
2155                 break;
2156         case PARTIAL_WORD:
2157                 // no need to move the 'from' cursor
2158                 break;
2159         }
2160         to = from;
2161         Paragraph & to_par = pars_[to.pit()];
2162         while (to.pos() < to_par.size() && to_par.isLetter(to.pos()))
2163                 ++to.pos();
2164 }
2165
2166
2167 void LyXText::write(Buffer const & buf, std::ostream & os) const
2168 {
2169         ParagraphList::const_iterator pit = paragraphs().begin();
2170         ParagraphList::const_iterator end = paragraphs().end();
2171         depth_type dth = 0;
2172         for (; pit != end; ++pit)
2173                 pit->write(buf, os, buf.params(), dth);
2174 }
2175
2176
2177 bool LyXText::read(Buffer const & buf, LyXLex & lex, ErrorList & errorList)
2178 {
2179         depth_type depth = 0;
2180
2181         while (lex.isOK()) {
2182                 lex.nextToken();
2183                 string const token = lex.getString();
2184
2185                 if (token.empty())
2186                         continue;
2187
2188                 if (token == "\\end_inset")
2189                         break;
2190
2191                 if (token == "\\end_body")
2192                         continue;
2193
2194                 if (token == "\\begin_body")
2195                         continue;
2196
2197                 if (token == "\\end_document")
2198                         return false;
2199
2200                 if (token == "\\begin_layout") {
2201                         lex.pushToken(token);
2202
2203                         Paragraph par;
2204                         par.params().depth(depth);
2205                         par.setFont(0, LyXFont(LyXFont::ALL_INHERIT, buf.params().language));
2206                         pars_.push_back(par);
2207
2208                         // FIXME: goddamn InsetTabular makes us pass a Buffer
2209                         // not BufferParams
2210                         lyx::readParagraph(buf, pars_.back(), lex, errorList);
2211
2212                 } else if (token == "\\begin_deeper") {
2213                         ++depth;
2214                 } else if (token == "\\end_deeper") {
2215                         if (!depth) {
2216                                 lex.printError("\\end_deeper: " "depth is already null");
2217                         } else {
2218                                 --depth;
2219                         }
2220                 } else {
2221                         lyxerr << "Handling unknown body token: `"
2222                                << token << '\'' << endl;
2223                 }
2224         }
2225         return true;
2226 }
2227
2228
2229 int LyXText::ascent() const
2230 {
2231         return dim_.asc;
2232 }
2233
2234
2235 int LyXText::descent() const
2236 {
2237         return dim_.des;
2238 }
2239
2240
2241 int LyXText::cursorX(CursorSlice const & sl, bool boundary) const
2242 {
2243         pit_type const pit = sl.pit();
2244         Paragraph const & par = pars_[pit];
2245         if (par.rows().empty())
2246                 return 0;
2247
2248         pos_type ppos = sl.pos();
2249         // Correct position in front of big insets
2250         bool const boundary_correction = ppos != 0 && boundary;
2251         if (boundary_correction)
2252                 --ppos;
2253
2254         Row const & row = par.getRow(sl.pos(), boundary);
2255
2256         pos_type cursor_vpos = 0;
2257
2258         RowMetrics const m = computeRowMetrics(pit, row);
2259         double x = m.x;
2260
2261         pos_type const row_pos  = row.pos();
2262         pos_type const end      = row.endpos();
2263
2264         if (end <= row_pos)
2265                 cursor_vpos = row_pos;
2266         else if (ppos >= end)
2267                 cursor_vpos = isRTL(par) ? row_pos : end;
2268         else if (ppos > row_pos && ppos >= end)
2269                 // Place cursor after char at (logical) position pos - 1
2270                 cursor_vpos = (bidi.level(ppos - 1) % 2 == 0)
2271                         ? bidi.log2vis(ppos - 1) + 1 : bidi.log2vis(ppos - 1);
2272         else
2273                 // Place cursor before char at (logical) position ppos
2274                 cursor_vpos = (bidi.level(ppos) % 2 == 0)
2275                         ? bidi.log2vis(ppos) : bidi.log2vis(ppos) + 1;
2276
2277         pos_type body_pos = par.beginOfBody();
2278         if (body_pos > 0 &&
2279             (body_pos > end || !par.isLineSeparator(body_pos - 1)))
2280                 body_pos = 0;
2281
2282         // Use font span to speed things up, see below
2283         FontSpan font_span;
2284         LyXFont font;
2285         FontMetrics const & labelfm = theFontMetrics(getLabelFont(par));
2286
2287         for (pos_type vpos = row_pos; vpos < cursor_vpos; ++vpos) {
2288                 pos_type pos = bidi.vis2log(vpos);
2289                 if (body_pos > 0 && pos == body_pos - 1) {
2290                         // FIXME UNICODE
2291                         docstring const lsep = from_utf8(par.layout()->labelsep);
2292                         x += m.label_hfill + labelfm.width(lsep);
2293                         if (par.isLineSeparator(body_pos - 1))
2294                                 x -= singleWidth(par, body_pos - 1);
2295                 }
2296
2297                 // Use font span to speed things up, see above
2298                 if (pos < font_span.first || pos > font_span.last) {
2299                         font_span = par.fontSpan(pos);
2300                         font = getFont(par, pos);
2301                 }
2302
2303                 x += singleWidth(par, pos, par.getChar(pos), font);
2304
2305                 if (par.hfillExpansion(row, pos))
2306                         x += (pos >= body_pos) ? m.hfill : m.label_hfill;
2307                 else if (par.isSeparator(pos) && pos >= body_pos)
2308                         x += m.separator;
2309         }
2310
2311         // see correction above
2312         if (boundary_correction)
2313                 if (getFont(par, ppos).isVisibleRightToLeft())
2314                         x -= singleWidth(par, ppos);
2315                 else
2316                         x += singleWidth(par, ppos);
2317
2318         // Make sure inside an inset we always count from the left
2319         // edge (bidi!) -- MV
2320         if (sl.pos() < par.size()) {
2321                 font = getFont(par, sl.pos());
2322                 if (!boundary && font.isVisibleRightToLeft()
2323                   && par.isInset(sl.pos()))
2324                         x -= par.getInset(sl.pos())->width();
2325         }
2326         return int(x);
2327 }
2328
2329
2330 int LyXText::cursorY(CursorSlice const & sl, bool boundary) const
2331 {
2332         //lyxerr << "LyXText::cursorY: boundary: " << boundary << std::endl;
2333         Paragraph const & par = getPar(sl.pit());
2334         if (par.rows().empty())
2335                 return 0;
2336
2337         int h = 0;
2338         h -= pars_[0].rows()[0].ascent();
2339         for (pit_type pit = 0; pit < sl.pit(); ++pit)
2340                 h += pars_[pit].height();
2341         int pos = sl.pos();
2342         if (pos && boundary)
2343                 --pos;
2344         size_t const rend = par.pos2row(pos);
2345         for (size_t rit = 0; rit != rend; ++rit)
2346                 h += par.rows()[rit].height();
2347         h += par.rows()[rend].ascent();
2348         return h;
2349 }
2350
2351
2352 // Returns the current font and depth as a message.
2353 string LyXText::currentState(LCursor & cur)
2354 {
2355         BOOST_ASSERT(this == cur.text());
2356         Buffer & buf = cur.buffer();
2357         Paragraph const & par = cur.paragraph();
2358         std::ostringstream os;
2359
2360         // FIXME: change tracking (MG)
2361         bool const show_change = par.lookupChange(cur.pos()) != Change(Change::UNCHANGED);
2362
2363         if (buf.params().trackChanges)
2364                 os << "[C] ";
2365
2366         if (show_change) {
2367                 Change change = par.lookupChange(cur.pos());
2368                 Author const & a = buf.params().authors().get(change.author);
2369                 os << to_utf8(_("Change: ")) << a.name();
2370                 if (!a.email().empty())
2371                         os << " (" << a.email() << ")";
2372                 if (change.changetime)
2373                         os << to_utf8(_(" at ")) << ctime(&change.changetime);
2374                 os << " : ";
2375         }
2376
2377         // I think we should only show changes from the default
2378         // font. (Asger)
2379         // No, from the document font (MV)
2380         LyXFont font = real_current_font;
2381         font.reduce(buf.params().getFont());
2382
2383         // avoid to_utf8(_(...)) re-entrance problem
2384         string const s = font.stateText(&buf.params());
2385         os << to_utf8(bformat(_("Font: %1$s"), from_utf8(s)));
2386
2387         // os << to_utf8(bformat(_("Font: %1$s"), font.stateText(&buf.params)));
2388
2389         // The paragraph depth
2390         int depth = cur.paragraph().getDepth();
2391         if (depth > 0)
2392                 os << to_utf8(bformat(_(", Depth: %1$d"), depth));
2393
2394         // The paragraph spacing, but only if different from
2395         // buffer spacing.
2396         Spacing const & spacing = par.params().spacing();
2397         if (!spacing.isDefault()) {
2398                 os << to_utf8(_(", Spacing: "));
2399                 switch (spacing.getSpace()) {
2400                 case Spacing::Single:
2401                         os << to_utf8(_("Single"));
2402                         break;
2403                 case Spacing::Onehalf:
2404                         os << to_utf8(_("OneHalf"));
2405                         break;
2406                 case Spacing::Double:
2407                         os << to_utf8(_("Double"));
2408                         break;
2409                 case Spacing::Other:
2410                         os << to_utf8(_("Other (")) << spacing.getValueAsString() << ')';
2411                         break;
2412                 case Spacing::Default:
2413                         // should never happen, do nothing
2414                         break;
2415                 }
2416         }
2417
2418 #ifdef DEVEL_VERSION
2419         os << to_utf8(_(", Inset: ")) << &cur.inset();
2420         os << to_utf8(_(", Paragraph: ")) << cur.pit();
2421         os << to_utf8(_(", Id: ")) << par.id();
2422         os << to_utf8(_(", Position: ")) << cur.pos();
2423         os << to_utf8(_(", Boundary: ")) << cur.boundary();
2424 //      Row & row = cur.textRow();
2425 //      os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
2426 #endif
2427         return os.str();
2428 }
2429
2430
2431 string LyXText::getPossibleLabel(LCursor & cur) const
2432 {
2433         pit_type pit = cur.pit();
2434
2435         LyXLayout_ptr layout = pars_[pit].layout();
2436
2437         if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
2438                 LyXLayout_ptr const & layout2 = pars_[pit - 1].layout();
2439                 if (layout2->latextype != LATEX_PARAGRAPH) {
2440                         --pit;
2441                         layout = layout2;
2442                 }
2443         }
2444
2445         string name = layout->latexname();
2446
2447         // for captions, we want the abbreviation of the float type
2448         if (layout->labeltype == LABEL_SENSITIVE) {
2449                 // Search for the first float or wrap inset in the iterator
2450                 size_t i = cur.depth();
2451                 while (i > 0) {
2452                         --i;
2453                         InsetBase * const in = &cur[i].inset();
2454                         if (in->lyxCode() == InsetBase::FLOAT_CODE
2455                             || in->lyxCode() == InsetBase::WRAP_CODE) {
2456                                 name = in->getInsetName();
2457                                 break;
2458                         }
2459                 }
2460         }
2461
2462         string text = name.substr(0, 3);
2463         if (name == "theorem")
2464                 text = "thm"; // Create a correct prefix for prettyref
2465
2466         text += ':';
2467         if (layout->latextype == LATEX_PARAGRAPH || lyxrc.label_init_length < 0)
2468                 text.erase();
2469
2470         // FIXME UNICODE
2471         string par_text = to_utf8(pars_[pit].asString(cur.buffer(), false));
2472         for (int i = 0; i < lyxrc.label_init_length; ++i) {
2473                 if (par_text.empty())
2474                         break;
2475                 string head;
2476                 par_text = split(par_text, head, ' ');
2477                 // Is it legal to use spaces in labels ?
2478                 if (i > 0)
2479                         text += '-';
2480                 text += head;
2481         }
2482
2483         return text;
2484 }
2485
2486
2487 //pos_type LyXText::x2pos(pit_type pit, int row, int x) const
2488 //{
2489 //      int lastx = 0;
2490 //      int currx = 0;
2491 //      Paragraph const & par = pars_[pit];
2492 //      Row const & r = par.rows()[row];
2493 //      int pos = r.pos();
2494 //      for (; currx < x && pos < r.endpos(); ++pos) {
2495 //              lastx = currx;
2496 //              currx += singleWidth(par, pos);
2497 //      }
2498 //      if (abs(lastx - x) < abs(currx - x) && pos != r.pos())
2499 //              --pos;
2500 //      return pos;
2501 //}
2502
2503
2504 pos_type LyXText::x2pos(pit_type pit, int row, int x) const
2505 {
2506         BOOST_ASSERT(row < int(pars_[pit].rows().size()));
2507         bool bound = false;
2508         Row const & r = pars_[pit].rows()[row];
2509         return r.pos() + getColumnNearX(pit, r, x, bound);
2510 }
2511
2512
2513 //int LyXText::pos2x(pit_type pit, pos_type pos) const
2514 //{
2515 //      Paragraph const & par = pars_[pit];
2516 //      Row const & r = par.rows()[row];
2517 //      int x = 0;
2518 //      pos -= r.pos();
2519 //}
2520
2521
2522 // x,y are screen coordinates
2523 // sets cursor only within this LyXText
2524 bool LyXText::setCursorFromCoordinates(LCursor & cur, int const x, int const y)
2525 {
2526         BOOST_ASSERT(this == cur.text());
2527         pit_type pit = getPitNearY(y);
2528         int yy = cur.bv().coordCache().get(this, pit).y_ - pars_[pit].ascent();
2529         lyxerr[Debug::DEBUG]
2530                 << BOOST_CURRENT_FUNCTION
2531                 << ": x: " << x
2532                 << " y: " << y
2533                 << " pit: " << pit
2534                 << " yy: " << yy << endl;
2535
2536         Paragraph const & par = pars_[pit];
2537         int r = 0;
2538         BOOST_ASSERT(par.rows().size());
2539         for (; r < int(par.rows().size()) - 1; ++r) {
2540                 Row const & row = par.rows()[r];
2541                 if (int(yy + row.height()) > y)
2542                         break;
2543                 yy += row.height();
2544         }
2545
2546         Row const & row = par.rows()[r];
2547
2548         lyxerr[Debug::DEBUG]
2549                 << BOOST_CURRENT_FUNCTION
2550                 << ": row " << r
2551                 << " from pos: " << row.pos()
2552                 << endl;
2553
2554         bool bound = false;
2555         int xx = x;
2556         pos_type const pos = row.pos() + getColumnNearX(pit, row, xx, bound);
2557
2558         lyxerr[Debug::DEBUG]
2559                 << BOOST_CURRENT_FUNCTION
2560                 << ": setting cursor pit: " << pit
2561                 << " pos: " << pos
2562                 << endl;
2563
2564         return setCursor(cur, pit, pos, true, bound);
2565 }
2566
2567
2568 } // namespace lyx