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