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