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