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