]> git.lyx.org Git - features.git/blob - src/text.C
change "support/std_sstream.h" to <sstream>
[features.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);
1238         setCharFont(pit, cur.pos(), rawtmpfont);
1239
1240         current_font = rawtmpfont;
1241         real_current_font = realtmpfont;
1242         redoParagraph(cur);
1243         setCursor(cur, cur.par(), cur.pos() + 1, false, cur.boundary());
1244         charInserted();
1245 }
1246
1247
1248 void LyXText::charInserted()
1249 {
1250         // Here we call finishUndo for every 20 characters inserted.
1251         // This is from my experience how emacs does it. (Lgb)
1252         static unsigned int counter;
1253         if (counter < 20) {
1254                 ++counter;
1255         } else {
1256                 finishUndo();
1257                 counter = 0;
1258         }
1259 }
1260
1261
1262 RowMetrics LyXText::computeRowMetrics(par_type pit, Row const & row) const
1263 {
1264         RowMetrics result;
1265
1266         double w = width_ - row.width();
1267
1268         bool const is_rtl = isRTL(pars_[pit]);
1269         if (is_rtl)
1270                 result.x = rightMargin(pars_[pit]);
1271         else
1272                 result.x = leftMargin(pit, row.pos());
1273
1274         // is there a manual margin with a manual label
1275         LyXLayout_ptr const & layout = pars_[pit].layout();
1276
1277         if (layout->margintype == MARGIN_MANUAL
1278             && layout->labeltype == LABEL_MANUAL) {
1279                 /// We might have real hfills in the label part
1280                 int nlh = numberOfLabelHfills(pars_[pit], row);
1281
1282                 // A manual label par (e.g. List) has an auto-hfill
1283                 // between the label text and the body of the
1284                 // paragraph too.
1285                 // But we don't want to do this auto hfill if the par
1286                 // is empty.
1287                 if (!pars_[pit].empty())
1288                         ++nlh;
1289
1290                 if (nlh && !pars_[pit].getLabelWidthString().empty())
1291                         result.label_hfill = labelFill(pit, row) / double(nlh);
1292         }
1293
1294         // are there any hfills in the row?
1295         int const nh = numberOfHfills(pars_[pit], row);
1296
1297         if (nh) {
1298                 if (w > 0)
1299                         result.hfill = w / nh;
1300         // we don't have to look at the alignment if it is ALIGN_LEFT and
1301         // if the row is already larger then the permitted width as then
1302         // we force the LEFT_ALIGN'edness!
1303         } else if (int(row.width()) < maxwidth_) {
1304                 // is it block, flushleft or flushright?
1305                 // set x how you need it
1306                 int align;
1307                 if (pars_[pit].params().align() == LYX_ALIGN_LAYOUT)
1308                         align = layout->align;
1309                 else
1310                         align = pars_[pit].params().align();
1311
1312                 // Display-style insets should always be on a centred row
1313                 // The test on pars_[pit].size() is to catch zero-size pars, which
1314                 // would trigger the assert in Paragraph::getInset().
1315                 //inset = pars_[pit].size() ? pars_[pit].getInset(row.pos()) : 0;
1316                 if (!pars_[pit].empty()
1317                     && pars_[pit].isInset(row.pos())
1318                     && pars_[pit].getInset(row.pos())->display())
1319                 {
1320                         align = LYX_ALIGN_CENTER;
1321                 }
1322
1323                 switch (align) {
1324                 case LYX_ALIGN_BLOCK: {
1325                         int const ns = numberOfSeparators(pars_[pit], row);
1326                         bool disp_inset = false;
1327                         if (row.endpos() < pars_[pit].size()) {
1328                                 InsetBase const * in = pars_[pit].getInset(row.endpos());
1329                                 if (in)
1330                                         disp_inset = in->display();
1331                         }
1332                         // If we have separators, this is not the last row of a
1333                         // par, does not end in newline, and is not row above a
1334                         // display inset... then stretch it
1335                         if (ns
1336                             && row.endpos() < pars_[pit].size()
1337                             && !pars_[pit].isNewline(row.endpos() - 1)
1338                             && !disp_inset
1339                                 ) {
1340                                 result.separator = w / ns;
1341                         } else if (is_rtl) {
1342                                 result.x += w;
1343                         }
1344                         break;
1345                 }
1346                 case LYX_ALIGN_RIGHT:
1347                         result.x += w;
1348                         break;
1349                 case LYX_ALIGN_CENTER:
1350                         result.x += w / 2;
1351                         break;
1352                 }
1353         }
1354
1355         bidi.computeTables(pars_[pit], *bv()->buffer(), row);
1356         if (is_rtl) {
1357                 pos_type body_pos = pars_[pit].beginOfBody();
1358                 pos_type end = row.endpos();
1359
1360                 if (body_pos > 0
1361                     && (body_pos > end || !pars_[pit].isLineSeparator(body_pos - 1)))
1362                 {
1363                         result.x += font_metrics::width(layout->labelsep, getLabelFont(pit));
1364                         if (body_pos <= end)
1365                                 result.x += result.label_hfill;
1366                 }
1367         }
1368
1369         return result;
1370 }
1371
1372
1373 // the cursor set functions have a special mechanism. When they
1374 // realize, that you left an empty paragraph, they will delete it.
1375
1376 void LyXText::cursorRightOneWord(LCursor & cur)
1377 {
1378         BOOST_ASSERT(this == cur.text());
1379         if (cur.pos() == cur.lastpos() && cur.par() != cur.lastpar()) {
1380                 ++cur.par();
1381                 cur.pos() = 0;
1382         } else {
1383                 // Skip through initial nonword stuff.
1384                 // Treat floats and insets as words.
1385                 while (cur.pos() != cur.lastpos() && !cur.paragraph().isWord(cur.pos()))
1386                         ++cur.pos();
1387                 // Advance through word.
1388                 while (cur.pos() != cur.lastpos() && cur.paragraph().isWord(cur.pos()))
1389                         ++cur.pos();
1390         }
1391         setCursor(cur, cur.par(), cur.pos());
1392 }
1393
1394
1395 void LyXText::cursorLeftOneWord(LCursor & cur)
1396 {
1397         BOOST_ASSERT(this == cur.text());
1398         if (cur.pos() == 0 && cur.par() != 0) {
1399                 --cur.par();
1400                 cur.pos() = cur.lastpos();
1401         } else {
1402                 // Skip through initial nonword stuff.
1403                 // Treat floats and insets as words.
1404                 while (cur.pos() != 0 && !cur.paragraph().isWord(cur.pos() - 1))
1405                         --cur.pos();
1406                 // Advance through word.
1407                 while (cur.pos() != 0 && cur.paragraph().isWord(cur.pos() - 1))
1408                         --cur.pos();
1409         }
1410         setCursor(cur, cur.par(), cur.pos());
1411 }
1412
1413
1414 void LyXText::selectWord(LCursor & cur, word_location loc)
1415 {
1416         BOOST_ASSERT(this == cur.text());
1417         CursorSlice from = cur.top();
1418         CursorSlice to = cur.top();
1419         getWord(from, to, loc);
1420         if (cur.top() != from)
1421                 setCursor(cur, from.par(), from.pos());
1422         if (to == from)
1423                 return;
1424         cur.resetAnchor();
1425         setCursor(cur, to.par(), to.pos());
1426         cur.setSelection();
1427 }
1428
1429
1430 // Select the word currently under the cursor when no
1431 // selection is currently set
1432 bool LyXText::selectWordWhenUnderCursor(LCursor & cur, word_location loc)
1433 {
1434         BOOST_ASSERT(this == cur.text());
1435         if (cur.selection())
1436                 return false;
1437         selectWord(cur, loc);
1438         return cur.selection();
1439 }
1440
1441
1442 void LyXText::acceptChange(LCursor & cur)
1443 {
1444         BOOST_ASSERT(this == cur.text());
1445         if (!cur.selection() && cur.lastpos() != 0)
1446                 return;
1447
1448         CursorSlice const & startc = cur.selBegin();
1449         CursorSlice const & endc = cur.selEnd();
1450         if (startc.par() == endc.par()) {
1451                 recordUndoSelection(cur, Undo::INSERT);
1452                 pars_[startc.par()].acceptChange(startc.pos(), endc.pos());
1453                 finishUndo();
1454                 cur.clearSelection();
1455                 redoParagraph(startc.par());
1456                 setCursorIntern(cur, startc.par(), 0);
1457         }
1458 #ifdef WITH_WARNINGS
1459 #warning handle multi par selection
1460 #endif
1461 }
1462
1463
1464 void LyXText::rejectChange(LCursor & cur)
1465 {
1466         BOOST_ASSERT(this == cur.text());
1467         if (!cur.selection() && cur.lastpos() != 0)
1468                 return;
1469
1470         CursorSlice const & startc = cur.selBegin();
1471         CursorSlice const & endc = cur.selEnd();
1472         if (startc.par() == endc.par()) {
1473                 recordUndoSelection(cur, Undo::INSERT);
1474                 pars_[startc.par()].rejectChange(startc.pos(), endc.pos());
1475                 finishUndo();
1476                 cur.clearSelection();
1477                 redoParagraph(startc.par());
1478                 setCursorIntern(cur, startc.par(), 0);
1479         }
1480 #ifdef WITH_WARNINGS
1481 #warning handle multi par selection
1482 #endif
1483 }
1484
1485
1486 // Delete from cursor up to the end of the current or next word.
1487 void LyXText::deleteWordForward(LCursor & cur)
1488 {
1489         BOOST_ASSERT(this == cur.text());
1490         if (cur.lastpos() == 0)
1491                 cursorRight(cur);
1492         else {
1493                 cur.resetAnchor();
1494                 cur.selection() = true;
1495                 cursorRightOneWord(cur);
1496                 cur.setSelection();
1497                 cutSelection(cur, true, false);
1498         }
1499 }
1500
1501
1502 // Delete from cursor to start of current or prior word.
1503 void LyXText::deleteWordBackward(LCursor & cur)
1504 {
1505         BOOST_ASSERT(this == cur.text());
1506         if (cur.lastpos() == 0)
1507                 cursorLeft(cur);
1508         else {
1509                 cur.resetAnchor();
1510                 cur.selection() = true;
1511                 cursorLeftOneWord(cur);
1512                 cur.setSelection();
1513                 cutSelection(cur, true, false);
1514         }
1515 }
1516
1517
1518 // Kill to end of line.
1519 void LyXText::deleteLineForward(LCursor & cur)
1520 {
1521         BOOST_ASSERT(this == cur.text());
1522         if (cur.lastpos() == 0) {
1523                 // Paragraph is empty, so we just go to the right
1524                 cursorRight(cur);
1525         } else {
1526                 cur.resetAnchor();
1527                 cur.selection() = true; // to avoid deletion
1528                 cursorEnd(cur);
1529                 cur.setSelection();
1530                 // What is this test for ??? (JMarc)
1531                 if (!cur.selection())
1532                         deleteWordForward(cur);
1533                 else
1534                         cutSelection(cur, true, false);
1535         }
1536 }
1537
1538
1539 void LyXText::changeCase(LCursor & cur, LyXText::TextCase action)
1540 {
1541         BOOST_ASSERT(this == cur.text());
1542         CursorSlice from;
1543         CursorSlice to;
1544
1545         if (cur.selection()) {
1546                 from = cur.selBegin();
1547                 to = cur.selEnd();
1548         } else {
1549                 from = cur.top();
1550                 getWord(from, to, lyx::PARTIAL_WORD);
1551                 setCursor(cur, to.par(), to.pos() + 1);
1552         }
1553
1554         recordUndoSelection(cur);
1555
1556         pos_type pos = from.pos();
1557         int par = from.par();
1558
1559         while (par != int(pars_.size()) && (pos != to.pos() || par != to.par())) {
1560                 par_type pit = par;
1561                 if (pos == pars_[pit].size()) {
1562                         ++par;
1563                         pos = 0;
1564                         continue;
1565                 }
1566                 unsigned char c = pars_[pit].getChar(pos);
1567                 if (c != Paragraph::META_INSET) {
1568                         switch (action) {
1569                         case text_lowercase:
1570                                 c = lowercase(c);
1571                                 break;
1572                         case text_capitalization:
1573                                 c = uppercase(c);
1574                                 action = text_lowercase;
1575                                 break;
1576                         case text_uppercase:
1577                                 c = uppercase(c);
1578                                 break;
1579                         }
1580                 }
1581 #ifdef WITH_WARNINGS
1582 #warning changes
1583 #endif
1584                 pars_[pit].setChar(pos, c);
1585                 ++pos;
1586         }
1587 }
1588
1589
1590 void LyXText::Delete(LCursor & cur)
1591 {
1592         BOOST_ASSERT(this == cur.text());
1593         if (cur.pos() != cur.lastpos()) {
1594                 recordUndo(cur, Undo::DELETE, cur.par());
1595                 setCursorIntern(cur, cur.par(), cur.pos() + 1, false, cur.boundary());
1596                 backspace(cur);
1597         }
1598         // should we do anything in an else branch?
1599 }
1600
1601
1602 void LyXText::backspace(LCursor & cur)
1603 {
1604         BOOST_ASSERT(this == cur.text());
1605         if (cur.pos() == 0) {
1606                 // The cursor is at the beginning of a paragraph, so
1607                 // the the backspace will collapse two paragraphs into
1608                 // one.
1609
1610                 // but it's not allowed unless it's new
1611                 Paragraph & par = cur.paragraph();
1612                 if (par.isChangeEdited(0, par.size()))
1613                         return;
1614
1615                 // we may paste some paragraphs
1616
1617                 // is it an empty paragraph?
1618                 pos_type lastpos = cur.lastpos();
1619                 if (lastpos == 0 || (lastpos == 1 && par.isSeparator(0))) {
1620                         // This is an empty paragraph and we delete it just
1621                         // by moving the cursor one step
1622                         // left and let the DeleteEmptyParagraphMechanism
1623                         // handle the actual deletion of the paragraph.
1624
1625                         if (cur.par() != 0) {
1626                                 cursorLeft(cur);
1627                                 // the layout things can change the height of a row !
1628                                 redoParagraph(cur);
1629                                 return;
1630                         }
1631                 }
1632
1633                 if (cur.par() != 0)
1634                         recordUndo(cur, Undo::DELETE, cur.par() - 1);
1635
1636                 par_type tmppit = cur.par();
1637                 // We used to do cursorLeftIntern() here, but it is
1638                 // not a good idea since it triggers the auto-delete
1639                 // mechanism. So we do a cursorLeftIntern()-lite,
1640                 // without the dreaded mechanism. (JMarc)
1641                 if (cur.par() != 0) {
1642                         // steps into the above paragraph.
1643                         setCursorIntern(cur, cur.par() - 1,
1644                                         pars_[cur.par() - 1].size(),
1645                                         false);
1646                 }
1647
1648                 // Pasting is not allowed, if the paragraphs have different
1649                 // layout. I think it is a real bug of all other
1650                 // word processors to allow it. It confuses the user.
1651                 // Correction: Pasting is always allowed with standard-layout
1652                 Buffer & buf = cur.buffer();
1653                 BufferParams const & bufparams = buf.params();
1654                 LyXTextClass const & tclass = bufparams.getLyXTextClass();
1655                 par_type const cpit = cur.par();
1656
1657                 if (cpit != tmppit
1658                     && (pars_[cpit].layout() == pars_[tmppit].layout()
1659                         || pars_[tmppit].layout() == tclass.defaultLayout())
1660                     && pars_[cpit].getAlign() == pars_[tmppit].getAlign()) {
1661                         mergeParagraph(bufparams, buf.paragraphs(), cpit);
1662
1663                         if (cur.pos() != 0 && pars_[cpit].isSeparator(cur.pos() - 1))
1664                                 --cur.pos();
1665
1666                         // the counters may have changed
1667                         updateCounters();
1668                         setCursor(cur, cur.par(), cur.pos(), false);
1669                 }
1670         } else {
1671                 // this is the code for a normal backspace, not pasting
1672                 // any paragraphs
1673                 recordUndo(cur, Undo::DELETE);
1674                 // We used to do cursorLeftIntern() here, but it is
1675                 // not a good idea since it triggers the auto-delete
1676                 // mechanism. So we do a cursorLeftIntern()-lite,
1677                 // without the dreaded mechanism. (JMarc)
1678                 setCursorIntern(cur, cur.par(), cur.pos() - 1,
1679                                 false, cur.boundary());
1680                 cur.paragraph().erase(cur.pos());
1681         }
1682
1683         if (cur.pos() == cur.lastpos())
1684                 setCurrentFont(cur);
1685
1686         redoParagraph(cur);
1687         setCursor(cur, cur.par(), cur.pos(), false, cur.boundary());
1688 }
1689
1690
1691 Paragraph & LyXText::getPar(par_type par) const
1692 {
1693         //lyxerr << "getPar: " << par << " from " << paragraphs().size() << endl;
1694         BOOST_ASSERT(par >= 0);
1695         BOOST_ASSERT(par < int(paragraphs().size()));
1696         return paragraphs()[par];
1697 }
1698
1699
1700 // y is relative to this LyXText's top
1701 Row const & LyXText::getRowNearY(int y, par_type & pit) const
1702 {
1703         BOOST_ASSERT(!paragraphs().empty());
1704         BOOST_ASSERT(!paragraphs().begin()->rows.empty());
1705         par_type const pend = paragraphs().size() - 1;
1706         pit = 0;
1707         while (int(pars_[pit].y + pars_[pit].height) < y && pit != pend)
1708                 ++pit;
1709
1710         RowList::iterator rit = pars_[pit].rows.end();
1711         RowList::iterator const rbegin = pars_[pit].rows.begin();
1712         do {
1713                 --rit;
1714         } while (rit != rbegin && int(pars_[pit].y + rit->y_offset()) > y);
1715
1716         return *rit;
1717 }
1718
1719
1720 Row const & LyXText::firstRow() const
1721 {
1722         return *paragraphs().front().rows.begin();
1723 }
1724
1725
1726 void LyXText::redoParagraphInternal(par_type pit)
1727 {
1728         // remove rows of paragraph, keep track of height changes
1729         height_ -= pars_[pit].height;
1730
1731         // clear old data
1732         pars_[pit].rows.clear();
1733         pars_[pit].height = 0;
1734         pars_[pit].width = 0;
1735
1736         // redo insets
1737         InsetList::iterator ii = pars_[pit].insetlist.begin();
1738         InsetList::iterator iend = pars_[pit].insetlist.end();
1739         for (; ii != iend; ++ii) {
1740                 Dimension dim;
1741                 int const w = maxwidth_ - leftMargin(pit) - rightMargin(pars_[pit]);
1742                 MetricsInfo mi(bv(), getFont(pit, ii->pos), w);
1743                 ii->inset->metrics(mi, dim);
1744         }
1745
1746         // rebreak the paragraph
1747         pars_[pit].setBeginOfBody();
1748         pos_type z = 0;
1749         do {
1750                 Row row(z);
1751                 rowBreakPoint(pit, row);
1752                 setRowWidth(pit, row);
1753                 setHeightOfRow(pit, row);
1754                 row.y_offset(pars_[pit].height);
1755                 pars_[pit].rows.push_back(row);
1756                 pars_[pit].width = std::max(pars_[pit].width, row.width());
1757                 pars_[pit].height += row.height();
1758                 z = row.endpos();
1759         } while (z < pars_[pit].size());
1760
1761         height_ += pars_[pit].height;
1762         //lyxerr << "redoParagraph: " << pars_[pit].rows.size() << " rows\n";
1763 }
1764
1765
1766 void LyXText::redoParagraphs(par_type pit, par_type end)
1767 {
1768         for ( ; pit != end; ++pit)
1769                 redoParagraphInternal(pit);
1770         updateParPositions();
1771         updateCounters();
1772 }
1773
1774
1775 void LyXText::redoParagraph(par_type pit)
1776 {
1777         redoParagraphInternal(pit);
1778         updateParPositions();
1779 }
1780
1781
1782 void LyXText::fullRebreak()
1783 {
1784         redoParagraphs(0, paragraphs().size());
1785         bv()->cursor().resetAnchor();
1786 }
1787
1788
1789 void LyXText::metrics(MetricsInfo & mi, Dimension & dim)
1790 {
1791         //BOOST_ASSERT(mi.base.textwidth);
1792         if (mi.base.textwidth)
1793                 maxwidth_ = mi.base.textwidth;
1794         //lyxerr << "LyXText::metrics: width: " << mi.base.textwidth
1795         //<< " maxWidth: " << maxwidth << "\nfont: " << mi.base.font
1796         //<< endl;
1797
1798         // Rebuild row cache. This recomputes height as well.
1799         redoParagraphs(0, paragraphs().size());
1800
1801         width_ = maxParagraphWidth(paragraphs());
1802
1803         // final dimension
1804         dim.asc = firstRow().ascent_of_text();
1805         dim.des = height_ - dim.asc;
1806         dim.wid = width_;
1807 }
1808
1809
1810 // only used for inset right now. should also be used for main text
1811 void LyXText::draw(PainterInfo & pi, int x, int y) const
1812 {
1813         xo_ = x;
1814         yo_ = y;
1815         paintTextInset(*this, pi);
1816 }
1817
1818
1819 // only used for inset right now. should also be used for main text
1820 void LyXText::drawSelection(PainterInfo &, int, int) const
1821 {
1822         //lyxerr << "LyXText::drawSelection at " << x << " " << y << endl;
1823 }
1824
1825
1826 bool LyXText::isLastRow(par_type pit, Row const & row) const
1827 {
1828         return row.endpos() >= pars_[pit].size()
1829                 && pit + 1 == par_type(paragraphs().size());
1830 }
1831
1832
1833 bool LyXText::isFirstRow(par_type pit, Row const & row) const
1834 {
1835         return row.pos() == 0 && pit == 0;
1836 }
1837
1838
1839 void LyXText::getWord(CursorSlice & from, CursorSlice & to,
1840         word_location const loc)
1841 {
1842         Paragraph & from_par = pars_[from.par()];
1843         switch (loc) {
1844         case lyx::WHOLE_WORD_STRICT:
1845                 if (from.pos() == 0 || from.pos() == from_par.size()
1846                     || !from_par.isWord(from.pos())
1847                     || !from_par.isWord(from.pos() - 1)) {
1848                         to = from;
1849                         return;
1850                 }
1851                 // no break here, we go to the next
1852
1853         case lyx::WHOLE_WORD:
1854                 // If we are already at the beginning of a word, do nothing
1855                 if (!from.pos() || !from_par.isWord(from.pos() - 1))
1856                         break;
1857                 // no break here, we go to the next
1858
1859         case lyx::PREVIOUS_WORD:
1860                 // always move the cursor to the beginning of previous word
1861                 while (from.pos() && from_par.isWord(from.pos() - 1))
1862                         --from.pos();
1863                 break;
1864         case lyx::NEXT_WORD:
1865                 lyxerr << "LyXText::getWord: NEXT_WORD not implemented yet"
1866                        << endl;
1867                 break;
1868         case lyx::PARTIAL_WORD:
1869                 // no need to move the 'from' cursor
1870                 break;
1871         }
1872         to = from;
1873         Paragraph & to_par = pars_[to.par()];
1874         while (to.pos() < to_par.size() && to_par.isWord(to.pos()))
1875                 ++to.pos();
1876 }
1877
1878
1879 void LyXText::write(Buffer const & buf, std::ostream & os) const
1880 {
1881         ParagraphList::const_iterator pit = paragraphs().begin();
1882         ParagraphList::const_iterator end = paragraphs().end();
1883         Paragraph::depth_type dth = 0;
1884         for (; pit != end; ++pit)
1885                 pit->write(buf, os, buf.params(), dth);
1886 }
1887
1888
1889 bool LyXText::read(Buffer const & buf, LyXLex & lex)
1890 {
1891         static Change current_change;
1892
1893         bool the_end_read = false;
1894         Paragraph::depth_type depth = 0;
1895
1896         while (lex.isOK()) {
1897                 lex.nextToken();
1898                 string token = lex.getString();
1899
1900                 if (token.empty())
1901                         continue;
1902
1903                 if (token == "\\end_inset") {
1904                         the_end_read = true;
1905                         break;
1906                 }
1907
1908                 if (token == "\\end_document") {
1909 #ifdef WITH_WARNINGS
1910 #warning Look here!
1911 #endif
1912 #if 0
1913                         lex.printError("\\end_document read in inset! Error in document!");
1914 #endif
1915                         return false;
1916                 }
1917
1918                 // FIXME: ugly.
1919                 int unknown = 0;
1920
1921                 if (token == "\\begin_layout") {
1922                         lex.pushToken(token);
1923
1924                         Paragraph par;
1925                         par.params().depth(depth);
1926                         if (buf.params().tracking_changes)
1927                                 par.trackChanges();
1928                         par.setFont(0, LyXFont(LyXFont::ALL_INHERIT, buf.params().language));
1929                         pars_.push_back(par);
1930
1931                         // FIXME: goddamn InsetTabular makes us pass a Buffer
1932                         // not BufferParams
1933                         ::readParagraph(buf, pars_.back(), lex);
1934
1935                 } else if (token == "\\begin_deeper") {
1936                         ++depth;
1937                 } else if (token == "\\end_deeper") {
1938                         if (!depth) {
1939                                 lex.printError("\\end_deeper: " "depth is already null");
1940                         } else {
1941                                 --depth;
1942                         }
1943                 } else {
1944                         ++unknown;
1945                 }
1946
1947         }
1948         return the_end_read;
1949 }
1950
1951
1952 int LyXText::ascent() const
1953 {
1954         return firstRow().ascent_of_text();
1955 }
1956
1957
1958 int LyXText::descent() const
1959 {
1960         return height_ - firstRow().ascent_of_text();
1961 }
1962
1963
1964 int LyXText::cursorX(CursorSlice const & cur) const
1965 {
1966         par_type pit = cur.par();
1967         if (pars_[pit].rows.empty())
1968                 return xo_;
1969
1970         Row const & row = *pars_[pit].getRow(cur.pos());
1971
1972         pos_type pos = cur.pos();
1973         pos_type cursor_vpos = 0;
1974
1975         RowMetrics const m = computeRowMetrics(pit, row);
1976         double x = m.x;
1977
1978         pos_type const row_pos  = row.pos();
1979         pos_type const end      = row.endpos();
1980
1981         if (end <= row_pos)
1982                 cursor_vpos = row_pos;
1983         else if (pos >= end)
1984                 cursor_vpos = isRTL(pars_[pit]) ? row_pos : end;
1985         else if (pos > row_pos && pos >= end)
1986                 // Place cursor after char at (logical) position pos - 1
1987                 cursor_vpos = (bidi.level(pos - 1) % 2 == 0)
1988                         ? bidi.log2vis(pos - 1) + 1 : bidi.log2vis(pos - 1);
1989         else
1990                 // Place cursor before char at (logical) position pos
1991                 cursor_vpos = (bidi.level(pos) % 2 == 0)
1992                         ? bidi.log2vis(pos) : bidi.log2vis(pos) + 1;
1993
1994         pos_type body_pos = pars_[pit].beginOfBody();
1995         if (body_pos > 0 &&
1996             (body_pos > end || !pars_[pit].isLineSeparator(body_pos - 1)))
1997                 body_pos = 0;
1998
1999         for (pos_type vpos = row_pos; vpos < cursor_vpos; ++vpos) {
2000                 pos_type pos = bidi.vis2log(vpos);
2001                 if (body_pos > 0 && pos == body_pos - 1) {
2002                         x += m.label_hfill
2003                                 + font_metrics::width(pars_[pit].layout()->labelsep,
2004                                                       getLabelFont(pit));
2005                         if (pars_[pit].isLineSeparator(body_pos - 1))
2006                                 x -= singleWidth(pit, body_pos - 1);
2007                 }
2008
2009                 if (hfillExpansion(pars_[pit], row, pos)) {
2010                         x += singleWidth(pit, pos);
2011                         if (pos >= body_pos)
2012                                 x += m.hfill;
2013                         else
2014                                 x += m.label_hfill;
2015                 } else if (pars_[pit].isSeparator(pos)) {
2016                         x += singleWidth(pit, pos);
2017                         if (pos >= body_pos)
2018                                 x += m.separator;
2019                 } else
2020                         x += singleWidth(pit, pos);
2021         }
2022         return xo_ + int(x);
2023 }
2024
2025
2026 int LyXText::cursorY(CursorSlice const & cur) const
2027 {
2028         Paragraph & par = getPar(cur.par());
2029         Row & row = *par.getRow(cur.pos());
2030         return yo_ + par.y + row.y_offset() + row.baseline();
2031 }
2032
2033
2034 // Returns the current font and depth as a message.
2035 string LyXText::currentState(LCursor & cur)
2036 {
2037         BOOST_ASSERT(this == cur.text());
2038         Buffer & buf = cur.buffer();
2039         Paragraph const & par = cur.paragraph();
2040         std::ostringstream os;
2041
2042         bool const show_change = buf.params().tracking_changes
2043                 && cur.pos() != cur.lastpos()
2044                 && par.lookupChange(cur.pos()) != Change::UNCHANGED;
2045
2046         if (show_change) {
2047                 Change change = par.lookupChangeFull(cur.pos());
2048                 Author const & a = buf.params().authors().get(change.author);
2049                 os << _("Change: ") << a.name();
2050                 if (!a.email().empty())
2051                         os << " (" << a.email() << ")";
2052                 if (change.changetime)
2053                         os << _(" at ") << ctime(&change.changetime);
2054                 os << " : ";
2055         }
2056
2057         // I think we should only show changes from the default
2058         // font. (Asger)
2059         LyXFont font = real_current_font;
2060         font.reduce(buf.params().getLyXTextClass().defaultfont());
2061
2062         // avoid _(...) re-entrance problem
2063         string const s = font.stateText(&buf.params());
2064         os << bformat(_("Font: %1$s"), s);
2065
2066         // os << bformat(_("Font: %1$s"), font.stateText(&buf.params));
2067
2068         // The paragraph depth
2069         int depth = cur.paragraph().getDepth();
2070         if (depth > 0)
2071                 os << bformat(_(", Depth: %1$s"), tostr(depth));
2072
2073         // The paragraph spacing, but only if different from
2074         // buffer spacing.
2075         Spacing const & spacing = par.params().spacing();
2076         if (!spacing.isDefault()) {
2077                 os << _(", Spacing: ");
2078                 switch (spacing.getSpace()) {
2079                 case Spacing::Single:
2080                         os << _("Single");
2081                         break;
2082                 case Spacing::Onehalf:
2083                         os << _("OneHalf");
2084                         break;
2085                 case Spacing::Double:
2086                         os << _("Double");
2087                         break;
2088                 case Spacing::Other:
2089                         os << _("Other (") << spacing.getValue() << ')';
2090                         break;
2091                 case Spacing::Default:
2092                         // should never happen, do nothing
2093                         break;
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 int LyXText::dist(int x, int y) const
2147 {
2148         int xx = 0;
2149         int yy = 0;
2150
2151         if (x < xo_)
2152                 xx = xo_ - x;
2153         else if (x > xo_ + int(width_))
2154                 xx = x - xo_ - width_;
2155
2156         if (y < yo_ - ascent())
2157                 yy = yo_ - ascent() - y;
2158         else if (y > yo_ + descent())
2159                 yy = y - yo_ - descent();
2160
2161         return xx + yy;
2162 }