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