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