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