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