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