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