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