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