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