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