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