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