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