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