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