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