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