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