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