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