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