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