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