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