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