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