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