]> git.lyx.org Git - lyx.git/blob - src/Text.cpp
Transfer current_font and real_current_font from Text to Cursor.
[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 "Cursor.h"
29 #include "ParIterator.h"
30 #include "CutAndPaste.h"
31 #include "debug.h"
32 #include "DispatchResult.h"
33 #include "Encoding.h"
34 #include "ErrorList.h"
35 #include "FuncRequest.h"
36 #include "factory.h"
37 #include "FontIterator.h"
38 #include "gettext.h"
39 #include "Language.h"
40 #include "Color.h"
41 #include "Length.h"
42 #include "Lexer.h"
43 #include "LyXRC.h"
44 #include "Paragraph.h"
45 #include "paragraph_funcs.h"
46 #include "ParagraphParameters.h"
47 #include "Undo.h"
48 #include "VSpace.h"
49 #include "WordLangTuple.h"
50
51 #include "frontends/FontMetrics.h"
52 #include "frontends/Painter.h"
53
54 #include "insets/InsetText.h"
55 #include "insets/InsetBibitem.h"
56 #include "insets/InsetCaption.h"
57 #include "insets/InsetHFill.h"
58 #include "insets/InsetLine.h"
59 #include "insets/InsetNewline.h"
60 #include "insets/InsetPagebreak.h"
61 #include "insets/InsetOptArg.h"
62 #include "insets/InsetSpace.h"
63 #include "insets/InsetSpecialChar.h"
64 #include "insets/InsetTabular.h"
65
66 #include "support/lstrings.h"
67 #include "support/textutils.h"
68 #include "support/convert.h"
69
70 #include <boost/current_function.hpp>
71
72 #include <sstream>
73
74 using std::auto_ptr;
75 using std::advance;
76 using std::distance;
77 using std::max;
78 using std::min;
79 using std::endl;
80 using std::string;
81
82 namespace lyx {
83
84 using support::bformat;
85 using support::contains;
86 using support::lowercase;
87 using support::split;
88 using support::uppercase;
89
90 using cap::cutSelection;
91 using cap::pasteParagraphList;
92
93 using frontend::FontMetrics;
94
95 namespace {
96
97 void readParToken(Buffer const & buf, Paragraph & par, Lexer & lex,
98         string const & token, Font & font, Change & change, ErrorList & errorList)
99 {
100         BufferParams const & bp = buf.params();
101
102         if (token[0] != '\\') {
103 #if 0
104                 string::const_iterator cit = token.begin();
105                 for (; cit != token.end(); ++cit)
106                         par.insertChar(par.size(), (*cit), font, change);
107 #else
108                 docstring dstr = lex.getDocString();
109                 docstring::const_iterator cit = dstr.begin();
110                 docstring::const_iterator cend = dstr.end();
111                 for (; cit != cend; ++cit)
112                         par.insertChar(par.size(), *cit, font, change);
113 #endif
114         } else if (token == "\\begin_layout") {
115                 lex.eatLine();
116                 docstring layoutname = lex.getDocString();
117
118                 font = Font(Font::ALL_INHERIT, bp.language);
119                 change = Change(Change::UNCHANGED);
120
121                 TextClass const & tclass = bp.getTextClass();
122
123                 if (layoutname.empty()) {
124                         layoutname = tclass.defaultLayoutName();
125                 }
126
127                 bool hasLayout = tclass.hasLayout(layoutname);
128
129                 if (!hasLayout) {
130                         errorList.push_back(ErrorItem(_("Unknown layout"),
131                         bformat(_("Layout '%1$s' does not exist in textclass '%2$s'\nTrying to use the default instead.\n"),
132                         layoutname, from_utf8(tclass.name())), par.id(), 0, par.size()));
133                         layoutname = tclass.defaultLayoutName();
134                 }
135
136                 par.layout(bp.getTextClass()[layoutname]);
137
138                 // Test whether the layout is obsolete.
139                 LayoutPtr const & layout = par.layout();
140                 if (!layout->obsoleted_by().empty())
141                         par.layout(bp.getTextClass()[layout->obsoleted_by()]);
142
143                 par.params().read(lex);
144
145         } else if (token == "\\end_layout") {
146                 lyxerr << BOOST_CURRENT_FUNCTION
147                        << ": Solitary \\end_layout in line "
148                        << lex.getLineNo() << "\n"
149                        << "Missing \\begin_layout?.\n";
150         } else if (token == "\\end_inset") {
151                 lyxerr << BOOST_CURRENT_FUNCTION
152                        << ": Solitary \\end_inset in line "
153                        << lex.getLineNo() << "\n"
154                        << "Missing \\begin_inset?.\n";
155         } else if (token == "\\begin_inset") {
156                 Inset * inset = readInset(lex, buf);
157                 if (inset)
158                         par.insertInset(par.size(), inset, font, change);
159                 else {
160                         lex.eatLine();
161                         docstring line = lex.getDocString();
162                         errorList.push_back(ErrorItem(_("Unknown Inset"), line,
163                                             par.id(), 0, par.size()));
164                 }
165         } else if (token == "\\family") {
166                 lex.next();
167                 font.setLyXFamily(lex.getString());
168         } else if (token == "\\series") {
169                 lex.next();
170                 font.setLyXSeries(lex.getString());
171         } else if (token == "\\shape") {
172                 lex.next();
173                 font.setLyXShape(lex.getString());
174         } else if (token == "\\size") {
175                 lex.next();
176                 font.setLyXSize(lex.getString());
177         } else if (token == "\\lang") {
178                 lex.next();
179                 string const tok = lex.getString();
180                 Language const * lang = languages.getLanguage(tok);
181                 if (lang) {
182                         font.setLanguage(lang);
183                 } else {
184                         font.setLanguage(bp.language);
185                         lex.printError("Unknown language `$$Token'");
186                 }
187         } else if (token == "\\numeric") {
188                 lex.next();
189                 font.setNumber(font.setLyXMisc(lex.getString()));
190         } else if (token == "\\emph") {
191                 lex.next();
192                 font.setEmph(font.setLyXMisc(lex.getString()));
193         } else if (token == "\\bar") {
194                 lex.next();
195                 string const tok = lex.getString();
196
197                 if (tok == "under")
198                         font.setUnderbar(Font::ON);
199                 else if (tok == "no")
200                         font.setUnderbar(Font::OFF);
201                 else if (tok == "default")
202                         font.setUnderbar(Font::INHERIT);
203                 else
204                         lex.printError("Unknown bar font flag "
205                                        "`$$Token'");
206         } else if (token == "\\noun") {
207                 lex.next();
208                 font.setNoun(font.setLyXMisc(lex.getString()));
209         } else if (token == "\\color") {
210                 lex.next();
211                 font.setLyXColor(lex.getString());
212         } else if (token == "\\InsetSpace" || token == "\\SpecialChar") {
213
214                 // Insets don't make sense in a free-spacing context! ---Kayvan
215                 if (par.isFreeSpacing()) {
216                         if (token == "\\InsetSpace")
217                                 par.insertChar(par.size(), ' ', font, change);
218                         else if (lex.isOK()) {
219                                 lex.next();
220                                 string const next_token = lex.getString();
221                                 if (next_token == "\\-")
222                                         par.insertChar(par.size(), '-', font, change);
223                                 else {
224                                         lex.printError("Token `$$Token' "
225                                                        "is in free space "
226                                                        "paragraph layout!");
227                                 }
228                         }
229                 } else {
230                         auto_ptr<Inset> inset;
231                         if (token == "\\SpecialChar" )
232                                 inset.reset(new InsetSpecialChar);
233                         else
234                                 inset.reset(new InsetSpace);
235                         inset->read(buf, lex);
236                         par.insertInset(par.size(), inset.release(),
237                                         font, change);
238                 }
239         } else if (token == "\\backslash") {
240                 par.insertChar(par.size(), '\\', font, change);
241         } else if (token == "\\newline") {
242                 auto_ptr<Inset> inset(new InsetNewline);
243                 inset->read(buf, lex);
244                 par.insertInset(par.size(), inset.release(), font, change);
245         } else if (token == "\\LyXTable") {
246                 auto_ptr<Inset> inset(new InsetTabular(buf));
247                 inset->read(buf, lex);
248                 par.insertInset(par.size(), inset.release(), font, change);
249         } else if (token == "\\hfill") {
250                 par.insertInset(par.size(), new InsetHFill, font, change);
251         } else if (token == "\\lyxline") {
252                 par.insertInset(par.size(), new InsetLine, font, change);
253         } else if (token == "\\newpage") {
254                 par.insertInset(par.size(), new InsetPagebreak, font, change);
255         } else if (token == "\\clearpage") {
256                 par.insertInset(par.size(), new InsetClearPage, font, change);
257         } else if (token == "\\cleardoublepage") {
258                 par.insertInset(par.size(), new InsetClearDoublePage, font, change);
259         } else if (token == "\\change_unchanged") {
260                 change = Change(Change::UNCHANGED);
261         } else if (token == "\\change_inserted") {
262                 lex.eatLine();
263                 std::istringstream is(lex.getString());
264                 unsigned int aid;
265                 time_type ct;
266                 is >> aid >> ct;
267                 if (aid >= bp.author_map.size()) {
268                         errorList.push_back(ErrorItem(_("Change tracking error"),
269                                             bformat(_("Unknown author index for insertion: %1$d\n"), aid),
270                                             par.id(), 0, par.size()));
271                         change = Change(Change::UNCHANGED);
272                 } else
273                         change = Change(Change::INSERTED, bp.author_map[aid], ct);
274         } else if (token == "\\change_deleted") {
275                 lex.eatLine();
276                 std::istringstream is(lex.getString());
277                 unsigned int aid;
278                 time_type ct;
279                 is >> aid >> ct;
280                 if (aid >= bp.author_map.size()) {
281                         errorList.push_back(ErrorItem(_("Change tracking error"),
282                                             bformat(_("Unknown author index for deletion: %1$d\n"), aid),
283                                             par.id(), 0, par.size()));
284                         change = Change(Change::UNCHANGED);
285                 } else
286                         change = Change(Change::DELETED, bp.author_map[aid], ct);
287         } else {
288                 lex.eatLine();
289                 errorList.push_back(ErrorItem(_("Unknown token"),
290                         bformat(_("Unknown token: %1$s %2$s\n"), from_utf8(token),
291                         lex.getDocString()),
292                         par.id(), 0, par.size()));
293         }
294 }
295
296
297 void readParagraph(Buffer const & buf, Paragraph & par, Lexer & lex,
298         ErrorList & errorList)
299 {
300         lex.nextToken();
301         string token = lex.getString();
302         Font font;
303         Change change(Change::UNCHANGED);
304
305         while (lex.isOK()) {
306                 readParToken(buf, par, lex, token, font, change, errorList);
307
308                 lex.nextToken();
309                 token = lex.getString();
310
311                 if (token.empty())
312                         continue;
313
314                 if (token == "\\end_layout") {
315                         //Ok, paragraph finished
316                         break;
317                 }
318
319                 LYXERR(Debug::PARSER) << "Handling paragraph token: `"
320                                       << token << '\'' << endl;
321                 if (token == "\\begin_layout" || token == "\\end_document"
322                     || token == "\\end_inset" || token == "\\begin_deeper"
323                     || token == "\\end_deeper") {
324                         lex.pushToken(token);
325                         lyxerr << "Paragraph ended in line "
326                                << lex.getLineNo() << "\n"
327                                << "Missing \\end_layout.\n";
328                         break;
329                 }
330         }
331         // Final change goes to paragraph break:
332         par.setChange(par.size(), change);
333
334         // Initialize begin_of_body_ on load; redoParagraph maintains
335         par.setBeginOfBody();
336 }
337
338
339 } // namespace anon
340
341
342 bool Text::empty() const
343 {
344         return pars_.empty() || (pars_.size() == 1 && pars_[0].empty()
345                 // FIXME: Should we consider the labeled type as empty too? 
346                 && pars_[0].layout()->labeltype == LABEL_NO_LABEL);
347 }
348
349
350 double Text::spacing(Buffer const & buffer,
351                 Paragraph const & par) const
352 {
353         if (par.params().spacing().isDefault())
354                 return buffer.params().spacing().getValue();
355         return par.params().spacing().getValue();
356 }
357
358
359 Color_color Text::backgroundColor() const
360 {
361         return Color_color(Color::color(background_color_));
362 }
363
364
365 void Text::breakParagraph(Cursor & cur, bool keep_layout)
366 {
367         BOOST_ASSERT(this == cur.text());
368
369         Paragraph & cpar = cur.paragraph();
370         pit_type cpit = cur.pit();
371
372         TextClass const & tclass = cur.buffer().params().getTextClass();
373         LayoutPtr const & layout = cpar.layout();
374
375         // this is only allowed, if the current paragraph is not empty
376         // or caption and if it has not the keepempty flag active
377         if (cur.lastpos() == 0 && !cpar.allowEmpty() &&
378             layout->labeltype != LABEL_SENSITIVE)
379                 return;
380
381         // a layout change may affect also the following paragraph
382         recUndo(cur, cur.pit(), undoSpan(cur.pit()) - 1);
383
384         // Always break behind a space
385         // It is better to erase the space (Dekel)
386         if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
387                 cpar.eraseChar(cur.pos(), cur.buffer().params().trackChanges);
388
389         // What should the layout for the new paragraph be?
390         int preserve_layout = 0;
391         if (keep_layout)
392                 preserve_layout = 2;
393         else
394                 preserve_layout = layout->isEnvironment();
395
396         // We need to remember this before we break the paragraph, because
397         // that invalidates the layout variable
398         bool sensitive = layout->labeltype == LABEL_SENSITIVE;
399
400         // we need to set this before we insert the paragraph.
401         bool const isempty = cpar.allowEmpty() && cpar.empty();
402
403         lyx::breakParagraph(cur.buffer().params(), paragraphs(), cpit,
404                          cur.pos(), preserve_layout);
405
406         // After this, neither paragraph contains any rows!
407
408         cpit = cur.pit();
409         pit_type next_par = cpit + 1;
410
411         // well this is the caption hack since one caption is really enough
412         if (sensitive) {
413                 if (cur.pos() == 0)
414                         // set to standard-layout
415                         pars_[cpit].applyLayout(tclass.defaultLayout());
416                 else
417                         // set to standard-layout
418                         pars_[next_par].applyLayout(tclass.defaultLayout());
419         }
420
421         while (!pars_[next_par].empty() && pars_[next_par].isNewline(0)) {
422                 if (!pars_[next_par].eraseChar(0, cur.buffer().params().trackChanges))
423                         break; // the character couldn't be deleted physically due to change tracking
424         }
425
426         updateLabels(cur.buffer());
427
428         // A singlePar update is not enough in this case.
429         cur.updateFlags(Update::Force);
430
431         // This check is necessary. Otherwise the new empty paragraph will
432         // be deleted automatically. And it is more friendly for the user!
433         if (cur.pos() != 0 || isempty)
434                 setCursor(cur, cur.pit() + 1, 0);
435         else
436                 setCursor(cur, cur.pit(), 0);
437 }
438
439
440 // insert a character, moves all the following breaks in the
441 // same Paragraph one to the right and make a rebreak
442 void Text::insertChar(Cursor & cur, char_type c)
443 {
444         BOOST_ASSERT(this == cur.text());
445         BOOST_ASSERT(c != Paragraph::META_INSET);
446
447         recordUndo(cur, Undo::INSERT);
448
449         Buffer const & buffer = cur.buffer();
450         Paragraph & par = cur.paragraph();
451         // try to remove this
452         pit_type const pit = cur.pit();
453
454         bool const freeSpacing = par.layout()->free_spacing ||
455                 par.isFreeSpacing();
456
457         if (lyxrc.auto_number) {
458                 static docstring const number_operators = from_ascii("+-/*");
459                 static docstring const number_unary_operators = from_ascii("+-");
460                 static docstring const number_seperators = from_ascii(".,:");
461
462                 if (cur.current_font.number() == Font::ON) {
463                         if (!isDigit(c) && !contains(number_operators, c) &&
464                             !(contains(number_seperators, c) &&
465                               cur.pos() != 0 &&
466                               cur.pos() != cur.lastpos() &&
467                               getFont(buffer, par, cur.pos()).number() == Font::ON &&
468                               getFont(buffer, par, cur.pos() - 1).number() == Font::ON)
469                            )
470                                 number(cur); // Set current_font.number to OFF
471                 } else if (isDigit(c) &&
472                            cur.real_current_font.isVisibleRightToLeft()) {
473                         number(cur); // Set current_font.number to ON
474
475                         if (cur.pos() != 0) {
476                                 char_type const c = par.getChar(cur.pos() - 1);
477                                 if (contains(number_unary_operators, c) &&
478                                     (cur.pos() == 1
479                                      || par.isSeparator(cur.pos() - 2)
480                                      || par.isNewline(cur.pos() - 2))
481                                   ) {
482                                         setCharFont(buffer, pit, cur.pos() - 1, cur.current_font);
483                                 } else if (contains(number_seperators, c)
484                                      && cur.pos() >= 2
485                                      && getFont(buffer, par, cur.pos() - 2).number() == Font::ON) {
486                                         setCharFont(buffer, pit, cur.pos() - 1, cur.current_font);
487                                 }
488                         }
489                 }
490         }
491
492         // In Bidi text, we want spaces to be treated in a special way: spaces
493         // which are between words in different languages should get the 
494         // paragraph's language; otherwise, spaces should keep the language 
495         // they were originally typed in. This is only in effect while typing;
496         // after the text is already typed in, the user can always go back and
497         // explicitly set the language of a space as desired. But 99.9% of the
498         // time, what we're doing here is what the user actually meant.
499         // 
500         // The following cases are the ones in which the language of the space
501         // should be changed to match that of the containing paragraph. In the
502         // depictions, lowercase is LTR, uppercase is RTL, underscore (_) 
503         // represents a space, pipe (|) represents the cursor position (so the
504         // character before it is the one just typed in). The different cases
505         // are depicted logically (not visually), from left to right:
506         // 
507         // 1. A_a|
508         // 2. a_A|
509         //
510         // Theoretically, there are other situations that we should, perhaps, deal
511         // with (e.g.: a|_A, A|_a). In practice, though, there really isn't any 
512         // point (to understand why, just try to create this situation...).
513
514         if ((cur.pos() >= 2) && (par.isLineSeparator(cur.pos() - 1))) {
515                 // get font in front and behind the space in question. But do NOT 
516                 // use getFont(cur.pos()) because the character c is not inserted yet
517                 Font const & pre_space_font  = getFont(buffer, par, cur.pos() - 2);
518                 Font const & post_space_font = cur.real_current_font;
519                 bool pre_space_rtl  = pre_space_font.isVisibleRightToLeft();
520                 bool post_space_rtl = post_space_font.isVisibleRightToLeft();
521                 
522                 if (pre_space_rtl != post_space_rtl) {
523                         // Set the space's language to match the language of the 
524                         // adjacent character whose direction is the paragraph's
525                         // direction; don't touch other properties of the font
526                         Language const * lang = 
527                                 (pre_space_rtl == par.isRightToLeftPar(buffer.params())) ?
528                                 pre_space_font.language() : post_space_font.language();
529
530                         Font space_font = getFont(buffer, par, cur.pos() - 1);
531                         space_font.setLanguage(lang);
532                         par.setFont(cur.pos() - 1, space_font);
533                 }
534         }
535         
536         // Next check, if there will be two blanks together or a blank at
537         // the beginning of a paragraph.
538         // I decided to handle blanks like normal characters, the main
539         // difference are the special checks when calculating the row.fill
540         // (blank does not count at the end of a row) and the check here
541
542         // When the free-spacing option is set for the current layout,
543         // disable the double-space checking
544         if (!freeSpacing && isLineSeparatorChar(c)) {
545                 if (cur.pos() == 0) {
546                         static bool sent_space_message = false;
547                         if (!sent_space_message) {
548                                 cur.message(_("You cannot insert a space at the "
549                                                            "beginning of a paragraph. Please read the Tutorial."));
550                                 sent_space_message = true;
551                         }
552                         return;
553                 }
554                 BOOST_ASSERT(cur.pos() > 0);
555                 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
556                     && !par.isDeleted(cur.pos() - 1)) {
557                         static bool sent_space_message = false;
558                         if (!sent_space_message) {
559                                 cur.message(_("You cannot type two spaces this way. "
560                                                            "Please read the Tutorial."));
561                                 sent_space_message = true;
562                         }
563                         return;
564                 }
565         }
566
567         par.insertChar(cur.pos(), c, cur.current_font, cur.buffer().params().trackChanges);
568         checkBufferStructure(cur.buffer(), cur);
569
570 //              cur.updateFlags(Update::Force);
571         setCursor(cur.top(), cur.pit(), cur.pos() + 1);
572         charInserted();
573 }
574
575
576 void Text::charInserted()
577 {
578         // Here we call finishUndo for every 20 characters inserted.
579         // This is from my experience how emacs does it. (Lgb)
580         static unsigned int counter;
581         if (counter < 20) {
582                 ++counter;
583         } else {
584                 finishUndo();
585                 counter = 0;
586         }
587 }
588
589
590 // the cursor set functions have a special mechanism. When they
591 // realize, that you left an empty paragraph, they will delete it.
592
593 bool Text::cursorRightOneWord(Cursor & cur)
594 {
595         BOOST_ASSERT(this == cur.text());
596
597         Cursor old = cur;
598
599         if (old.pos() == old.lastpos() && old.pit() != old.lastpit()) {
600                 ++old.pit();
601                 old.pos() = 0;
602         } else {
603                 // Advance through word.
604                 while (old.pos() != old.lastpos() && old.paragraph().isLetter(old.pos()))
605                         ++old.pos();
606                 // Skip through trailing nonword stuff.
607                 while (old.pos() != old.lastpos() && !old.paragraph().isLetter(old.pos()))
608                         ++old.pos();
609         }
610         return setCursor(cur, old.pit(), old.pos());
611 }
612
613
614 bool Text::cursorLeftOneWord(Cursor & cur)
615 {
616         BOOST_ASSERT(this == cur.text());
617
618         Cursor old = cur;
619
620         if (old.pos() == 0 && old.pit() != 0) {
621                 --old.pit();
622                 old.pos() = old.lastpos();
623         } else {
624                 // Skip through initial nonword stuff.
625                 while (old.pos() != 0 && !old.paragraph().isLetter(old.pos() - 1))
626                         --old.pos();
627                 // Advance through word.
628                 while (old.pos() != 0 && old.paragraph().isLetter(old.pos() - 1))
629                         --old.pos();
630         }
631         return setCursor(cur, old.pit(), old.pos());
632 }
633
634
635 void Text::selectWord(Cursor & cur, word_location loc)
636 {
637         BOOST_ASSERT(this == cur.text());
638         CursorSlice from = cur.top();
639         CursorSlice to = cur.top();
640         getWord(from, to, loc);
641         if (cur.top() != from)
642                 setCursor(cur, from.pit(), from.pos());
643         if (to == from)
644                 return;
645         cur.resetAnchor();
646         setCursor(cur, to.pit(), to.pos());
647         cur.setSelection();
648 }
649
650
651 // Select the word currently under the cursor when no
652 // selection is currently set
653 bool Text::selectWordWhenUnderCursor(Cursor & cur, word_location loc)
654 {
655         BOOST_ASSERT(this == cur.text());
656         if (cur.selection())
657                 return false;
658         selectWord(cur, loc);
659         return cur.selection();
660 }
661
662
663 void Text::acceptOrRejectChanges(Cursor & cur, ChangeOp op)
664 {
665         BOOST_ASSERT(this == cur.text());
666
667         if (!cur.selection())
668                 return;
669
670         recordUndoSelection(cur, Undo::ATOMIC);
671
672         pit_type begPit = cur.selectionBegin().pit();
673         pit_type endPit = cur.selectionEnd().pit();
674
675         pos_type begPos = cur.selectionBegin().pos();
676         pos_type endPos = cur.selectionEnd().pos();
677
678         // keep selection info, because endPos becomes invalid after the first loop
679         bool endsBeforeEndOfPar = (endPos < pars_[endPit].size());
680
681         // first, accept/reject changes within each individual paragraph (do not consider end-of-par)
682
683         for (pit_type pit = begPit; pit <= endPit; ++pit) {
684                 pos_type parSize = pars_[pit].size();
685
686                 // ignore empty paragraphs; otherwise, an assertion will fail for
687                 // acceptChanges(bparams, 0, 0) or rejectChanges(bparams, 0, 0)
688                 if (parSize == 0)
689                         continue;
690
691                 // do not consider first paragraph if the cursor starts at pos size()
692                 if (pit == begPit && begPos == parSize)
693                         continue;
694
695                 // do not consider last paragraph if the cursor ends at pos 0
696                 if (pit == endPit && endPos == 0)
697                         break; // last iteration anyway
698
699                 pos_type left  = (pit == begPit ? begPos : 0);
700                 pos_type right = (pit == endPit ? endPos : parSize);
701
702                 if (op == ACCEPT) {
703                         pars_[pit].acceptChanges(cur.buffer().params(), left, right);
704                 } else {
705                         pars_[pit].rejectChanges(cur.buffer().params(), left, right);
706                 }
707         }
708
709         // next, accept/reject imaginary end-of-par characters
710
711         for (pit_type pit = begPit; pit <= endPit; ++pit) {
712                 pos_type pos = pars_[pit].size();
713
714                 // skip if the selection ends before the end-of-par
715                 if (pit == endPit && endsBeforeEndOfPar)
716                         break; // last iteration anyway
717
718                 // skip if this is not the last paragraph of the document
719                 // note: the user should be able to accept/reject the par break of the last par!
720                 if (pit == endPit && pit + 1 != int(pars_.size()))
721                         break; // last iteration anway
722
723                 if (op == ACCEPT) {
724                         if (pars_[pit].isInserted(pos)) {
725                                 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
726                         } else if (pars_[pit].isDeleted(pos)) {
727                                 if (pit + 1 == int(pars_.size())) {
728                                         // we cannot remove a par break at the end of the last paragraph;
729                                         // instead, we mark it unchanged
730                                         pars_[pit].setChange(pos, Change(Change::UNCHANGED));
731                                 } else {
732                                         mergeParagraph(cur.buffer().params(), pars_, pit);
733                                         --endPit;
734                                         --pit;
735                                 }
736                         }
737                 } else {
738                         if (pars_[pit].isDeleted(pos)) {
739                                 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
740                         } else if (pars_[pit].isInserted(pos)) {
741                                 if (pit + 1 == int(pars_.size())) {
742                                         // we mark the par break at the end of the last paragraph unchanged
743                                         pars_[pit].setChange(pos, Change(Change::UNCHANGED));
744                                 } else {
745                                         mergeParagraph(cur.buffer().params(), pars_, pit);
746                                         --endPit;
747                                         --pit;
748                                 }
749                         }
750                 }
751         }
752
753         // finally, invoke the DEPM
754
755         deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer().params().trackChanges);
756
757         //
758
759         finishUndo();
760         cur.clearSelection();
761         setCursorIntern(cur, begPit, begPos);
762         cur.updateFlags(Update::Force);
763         updateLabels(cur.buffer());
764 }
765
766
767 void Text::acceptChanges(BufferParams const & bparams)
768 {
769         lyx::acceptChanges(pars_, bparams);
770         deleteEmptyParagraphMechanism(0, pars_.size() - 1, bparams.trackChanges);
771 }
772
773
774 void Text::rejectChanges(BufferParams const & bparams)
775 {
776         pit_type pars_size = static_cast<pit_type>(pars_.size());
777
778         // first, reject changes within each individual paragraph
779         // (do not consider end-of-par)
780         for (pit_type pit = 0; pit < pars_size; ++pit) {
781                 if (!pars_[pit].empty())   // prevent assertion failure
782                         pars_[pit].rejectChanges(bparams, 0, pars_[pit].size());
783         }
784
785         // next, reject imaginary end-of-par characters
786         for (pit_type pit = 0; pit < pars_size; ++pit) {
787                 pos_type pos = pars_[pit].size();
788
789                 if (pars_[pit].isDeleted(pos)) {
790                         pars_[pit].setChange(pos, Change(Change::UNCHANGED));
791                 } else if (pars_[pit].isInserted(pos)) {
792                         if (pit == pars_size - 1) {
793                                 // we mark the par break at the end of the last
794                                 // paragraph unchanged
795                                 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
796                         } else {
797                                 mergeParagraph(bparams, pars_, pit);
798                                 --pit;
799                                 --pars_size;
800                         }
801                 }
802         }
803
804         // finally, invoke the DEPM
805         deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.trackChanges);
806 }
807
808
809 void Text::deleteWordForward(Cursor & cur)
810 {
811         BOOST_ASSERT(this == cur.text());
812         if (cur.lastpos() == 0)
813                 cursorRight(cur);
814         else {
815                 cur.resetAnchor();
816                 cur.selection() = true;
817                 cursorRightOneWord(cur);
818                 cur.setSelection();
819                 cutSelection(cur, true, false);
820                 checkBufferStructure(cur.buffer(), cur);
821         }
822 }
823
824
825 void Text::deleteWordBackward(Cursor & cur)
826 {
827         BOOST_ASSERT(this == cur.text());
828         if (cur.lastpos() == 0)
829                 cursorLeft(cur);
830         else {
831                 cur.resetAnchor();
832                 cur.selection() = true;
833                 cursorLeftOneWord(cur);
834                 cur.setSelection();
835                 cutSelection(cur, true, false);
836                 checkBufferStructure(cur.buffer(), cur);
837         }
838 }
839
840
841 // Kill to end of line.
842 void Text::changeCase(Cursor & cur, Text::TextCase action)
843 {
844         BOOST_ASSERT(this == cur.text());
845         CursorSlice from;
846         CursorSlice to;
847
848         if (cur.selection()) {
849                 from = cur.selBegin();
850                 to = cur.selEnd();
851         } else {
852                 from = cur.top();
853                 getWord(from, to, PARTIAL_WORD);
854                 cursorRightOneWord(cur);
855         }
856
857         recordUndoSelection(cur, Undo::ATOMIC);
858
859         pit_type begPit = from.pit();
860         pit_type endPit = to.pit();
861
862         pos_type begPos = from.pos();
863         pos_type endPos = to.pos();
864
865         bool const trackChanges = cur.buffer().params().trackChanges;
866
867         pos_type right = 0; // needed after the for loop
868
869         for (pit_type pit = begPit; pit <= endPit; ++pit) {
870                 pos_type parSize = pars_[pit].size();
871
872                 pos_type pos = (pit == begPit ? begPos : 0);
873                 right = (pit == endPit ? endPos : parSize);
874
875                 // process sequences of modified characters; in change
876                 // tracking mode, this approach results in much better
877                 // usability than changing case on a char-by-char basis
878                 docstring changes;
879
880                 bool capitalize = true;
881
882                 for (; pos < right; ++pos) {
883                         char_type oldChar = pars_[pit].getChar(pos);
884                         char_type newChar = oldChar;
885
886                         // ignore insets and don't play with deleted text!
887                         if (oldChar != Paragraph::META_INSET && !pars_[pit].isDeleted(pos)) {
888                                 switch (action) {
889                                 case text_lowercase:
890                                         newChar = lowercase(oldChar);
891                                         break;
892                                 case text_capitalization:
893                                         if (capitalize) {
894                                                 newChar = uppercase(oldChar);
895                                                 capitalize = false;
896                                         }
897                                         break;
898                                 case text_uppercase:
899                                         newChar = uppercase(oldChar);
900                                         break;
901                                 }
902                         }
903
904                         if (!pars_[pit].isLetter(pos) || pars_[pit].isDeleted(pos)) {
905                                 capitalize = true; // permit capitalization again
906                         }
907
908                         if (oldChar != newChar) {
909                                 changes += newChar;
910                         }
911
912                         if (oldChar == newChar || pos == right - 1) {
913                                 if (oldChar != newChar) {
914                                         pos++; // step behind the changing area
915                                 }
916                                 int erasePos = pos - changes.size();
917                                 for (size_t i = 0; i < changes.size(); i++) {
918                                         pars_[pit].insertChar(pos, changes[i],
919                                                 pars_[pit].getFontSettings(cur.buffer().params(),
920                                                                 erasePos),
921                                                 trackChanges);
922                                         if (!pars_[pit].eraseChar(erasePos, trackChanges)) {
923                                                 ++erasePos;
924                                                 ++pos; // advance
925                                                 ++right; // expand selection
926                                         }
927                                 }
928                                 changes.clear();
929                         }
930                 }
931         }
932
933         // the selection may have changed due to logically-only deleted chars
934         setCursor(cur, begPit, begPos);
935         cur.resetAnchor();
936         setCursor(cur, endPit, right);
937         cur.setSelection();
938
939         checkBufferStructure(cur.buffer(), cur);
940 }
941
942
943 bool Text::handleBibitems(Cursor & cur)
944 {
945         if (cur.paragraph().layout()->labeltype != LABEL_BIBLIO)
946                 return false;
947         // if a bibitem is deleted, merge with previous paragraph
948         // if this is a bibliography item as well
949         if (cur.pos() == 0) {
950                 BufferParams const & bufparams = cur.buffer().params();
951                 Paragraph const & par = cur.paragraph();
952                 Cursor prevcur = cur;
953                 if (cur.pit() > 0) {
954                         --prevcur.pit();
955                         prevcur.pos() = prevcur.lastpos();
956                 }
957                 Paragraph const & prevpar = prevcur.paragraph();
958                 if (cur.pit() > 0 && par.layout() == prevpar.layout()) {
959                         recordUndo(cur, Undo::ATOMIC, prevcur.pit());
960                         mergeParagraph(bufparams, cur.text()->paragraphs(),
961                                        prevcur.pit());
962                         updateLabels(cur.buffer());
963                         setCursorIntern(cur, prevcur.pit(), prevcur.pos());
964                         cur.updateFlags(Update::Force);
965                 // if not, reset the paragraph to default
966                 } else
967                         cur.paragraph().layout(
968                                 bufparams.getTextClass().defaultLayout());
969                 return true;
970         }
971         return false;
972 }
973
974
975 bool Text::erase(Cursor & cur)
976 {
977         BOOST_ASSERT(this == cur.text());
978         bool needsUpdate = false;
979         Paragraph & par = cur.paragraph();
980
981         if (cur.pos() != cur.lastpos()) {
982                 // this is the code for a normal delete, not pasting
983                 // any paragraphs
984                 recordUndo(cur, Undo::DELETE);
985                 if(!par.eraseChar(cur.pos(), cur.buffer().params().trackChanges)) {
986                         // the character has been logically deleted only => skip it
987                         cur.top().forwardPos();
988                 }
989                 checkBufferStructure(cur.buffer(), cur);
990                 needsUpdate = true;
991         } else {
992                 if (cur.pit() == cur.lastpit())
993                         return dissolveInset(cur);
994
995                 if (!par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
996                         par.setChange(cur.pos(), Change(Change::DELETED));
997                         cur.forwardPos();
998                         needsUpdate = true;
999                 } else {
1000                         setCursorIntern(cur, cur.pit() + 1, 0);
1001                         needsUpdate = backspacePos0(cur);
1002                 }
1003         }
1004
1005         needsUpdate |= handleBibitems(cur);
1006
1007         if (needsUpdate) {
1008                 // Make sure the cursor is correct. Is this really needed?
1009                 // No, not really... at least not here!
1010                 cur.text()->setCursor(cur.top(), cur.pit(), cur.pos());
1011                 checkBufferStructure(cur.buffer(), cur);
1012         }
1013
1014         return needsUpdate;
1015 }
1016
1017
1018 bool Text::backspacePos0(Cursor & cur)
1019 {
1020         BOOST_ASSERT(this == cur.text());
1021         if (cur.pit() == 0)
1022                 return false;
1023
1024         bool needsUpdate = false;
1025
1026         BufferParams const & bufparams = cur.buffer().params();
1027         TextClass const & tclass = bufparams.getTextClass();
1028         ParagraphList & plist = cur.text()->paragraphs();
1029         Paragraph const & par = cur.paragraph();
1030         Cursor prevcur = cur;
1031         --prevcur.pit();
1032         prevcur.pos() = prevcur.lastpos();
1033         Paragraph const & prevpar = prevcur.paragraph();
1034
1035         // is it an empty paragraph?
1036         if (cur.lastpos() == 0
1037             || (cur.lastpos() == 1 && par.isSeparator(0))) {
1038                 recordUndo(cur, Undo::ATOMIC, prevcur.pit(), cur.pit());
1039                 plist.erase(boost::next(plist.begin(), cur.pit()));
1040                 needsUpdate = true;
1041         }
1042         // is previous par empty?
1043         else if (prevcur.lastpos() == 0
1044                  || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
1045                 recordUndo(cur, Undo::ATOMIC, prevcur.pit(), cur.pit());
1046                 plist.erase(boost::next(plist.begin(), prevcur.pit()));
1047                 needsUpdate = true;
1048         }
1049         // Pasting is not allowed, if the paragraphs have different
1050         // layouts. I think it is a real bug of all other
1051         // word processors to allow it. It confuses the user.
1052         // Correction: Pasting is always allowed with standard-layout
1053         else if (par.layout() == prevpar.layout()
1054                  || par.layout() == tclass.defaultLayout()) {
1055                 recordUndo(cur, Undo::ATOMIC, prevcur.pit());
1056                 mergeParagraph(bufparams, plist, prevcur.pit());
1057                 needsUpdate = true;
1058         }
1059
1060         if (needsUpdate) {
1061                 updateLabels(cur.buffer());
1062                 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1063         }
1064
1065         return needsUpdate;
1066 }
1067
1068
1069 bool Text::backspace(Cursor & cur)
1070 {
1071         BOOST_ASSERT(this == cur.text());
1072         bool needsUpdate = false;
1073         if (cur.pos() == 0) {
1074                 if (cur.pit() == 0)
1075                         return dissolveInset(cur);
1076
1077                 Paragraph & prev_par = pars_[cur.pit() - 1];
1078
1079                 if (!prev_par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
1080                         prev_par.setChange(prev_par.size(), Change(Change::DELETED));
1081                         setCursorIntern(cur, cur.pit() - 1, prev_par.size());
1082                         return true;
1083                 }
1084                 // The cursor is at the beginning of a paragraph, so
1085                 // the backspace will collapse two paragraphs into one.
1086                 needsUpdate = backspacePos0(cur);
1087
1088         } else {
1089                 // this is the code for a normal backspace, not pasting
1090                 // any paragraphs
1091                 recordUndo(cur, Undo::DELETE);
1092                 // We used to do cursorLeftIntern() here, but it is
1093                 // not a good idea since it triggers the auto-delete
1094                 // mechanism. So we do a cursorLeftIntern()-lite,
1095                 // without the dreaded mechanism. (JMarc)
1096                 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1097                                 false, cur.boundary());
1098                 cur.paragraph().eraseChar(cur.pos(), cur.buffer().params().trackChanges);
1099                 checkBufferStructure(cur.buffer(), cur);
1100         }
1101
1102         if (cur.pos() == cur.lastpos())
1103                 cur.setCurrentFont();
1104
1105         needsUpdate |= handleBibitems(cur);
1106
1107         // A singlePar update is not enough in this case.
1108 //              cur.updateFlags(Update::Force);
1109         setCursor(cur.top(), cur.pit(), cur.pos());
1110
1111         return needsUpdate;
1112 }
1113
1114
1115 bool Text::dissolveInset(Cursor & cur) {
1116         BOOST_ASSERT(this == cur.text());
1117
1118         if (isMainText(cur.bv().buffer()) || cur.inset().nargs() != 1)
1119                 return false;
1120
1121         recordUndoInset(cur);
1122         cur.selHandle(false);
1123         // save position
1124         pos_type spos = cur.pos();
1125         pit_type spit = cur.pit();
1126         ParagraphList plist;
1127         if (cur.lastpit() != 0 || cur.lastpos() != 0)
1128                 plist = paragraphs();
1129         cur.popLeft();
1130         // store cursor offset
1131         if (spit == 0)
1132                 spos += cur.pos();
1133         spit += cur.pit();
1134         Buffer & b = cur.buffer();
1135         cur.paragraph().eraseChar(cur.pos(), b.params().trackChanges);
1136         if (!plist.empty()) {
1137                 // ERT paragraphs have the Language latex_language.
1138                 // This is invalid outside of ERT, so we need to
1139                 // change it to the buffer language.
1140                 ParagraphList::iterator it = plist.begin();
1141                 ParagraphList::iterator it_end = plist.end();
1142                 for (; it != it_end; it++) {
1143                         it->changeLanguage(b.params(), latex_language,
1144                                         b.getLanguage());
1145                 }
1146
1147                 pasteParagraphList(cur, plist, b.params().getTextClass_ptr(),
1148                                    b.errorList("Paste"));
1149                 // restore position
1150                 cur.pit() = std::min(cur.lastpit(), spit);
1151                 cur.pos() = std::min(cur.lastpos(), spos);
1152         }
1153         cur.clearSelection();
1154         cur.resetAnchor();
1155         return true;
1156 }
1157
1158
1159 void Text::getWord(CursorSlice & from, CursorSlice & to,
1160         word_location const loc)
1161 {
1162         Paragraph const & from_par = pars_[from.pit()];
1163         switch (loc) {
1164         case WHOLE_WORD_STRICT:
1165                 if (from.pos() == 0 || from.pos() == from_par.size()
1166                     || !from_par.isLetter(from.pos())
1167                     || !from_par.isLetter(from.pos() - 1)) {
1168                         to = from;
1169                         return;
1170                 }
1171                 // no break here, we go to the next
1172
1173         case WHOLE_WORD:
1174                 // If we are already at the beginning of a word, do nothing
1175                 if (!from.pos() || !from_par.isLetter(from.pos() - 1))
1176                         break;
1177                 // no break here, we go to the next
1178
1179         case PREVIOUS_WORD:
1180                 // always move the cursor to the beginning of previous word
1181                 while (from.pos() && from_par.isLetter(from.pos() - 1))
1182                         --from.pos();
1183                 break;
1184         case NEXT_WORD:
1185                 lyxerr << "Text::getWord: NEXT_WORD not implemented yet"
1186                        << endl;
1187                 break;
1188         case PARTIAL_WORD:
1189                 // no need to move the 'from' cursor
1190                 break;
1191         }
1192         to = from;
1193         Paragraph & to_par = pars_[to.pit()];
1194         while (to.pos() < to_par.size() && to_par.isLetter(to.pos()))
1195                 ++to.pos();
1196 }
1197
1198
1199 void Text::write(Buffer const & buf, std::ostream & os) const
1200 {
1201         ParagraphList::const_iterator pit = paragraphs().begin();
1202         ParagraphList::const_iterator end = paragraphs().end();
1203         depth_type dth = 0;
1204         for (; pit != end; ++pit)
1205                 pit->write(buf, os, buf.params(), dth);
1206
1207         // Close begin_deeper
1208         for(; dth > 0; --dth)
1209                 os << "\n\\end_deeper";
1210 }
1211
1212
1213 bool Text::read(Buffer const & buf, Lexer & lex, ErrorList & errorList)
1214 {
1215         depth_type depth = 0;
1216
1217         while (lex.isOK()) {
1218                 lex.nextToken();
1219                 string const token = lex.getString();
1220
1221                 if (token.empty())
1222                         continue;
1223
1224                 if (token == "\\end_inset")
1225                         break;
1226
1227                 if (token == "\\end_body")
1228                         continue;
1229
1230                 if (token == "\\begin_body")
1231                         continue;
1232
1233                 if (token == "\\end_document")
1234                         return false;
1235
1236                 if (token == "\\begin_layout") {
1237                         lex.pushToken(token);
1238
1239                         Paragraph par;
1240                         par.params().depth(depth);
1241                         par.setFont(0, Font(Font::ALL_INHERIT, buf.params().language));
1242                         pars_.push_back(par);
1243
1244                         // FIXME: goddamn InsetTabular makes us pass a Buffer
1245                         // not BufferParams
1246                         lyx::readParagraph(buf, pars_.back(), lex, errorList);
1247
1248                 } else if (token == "\\begin_deeper") {
1249                         ++depth;
1250                 } else if (token == "\\end_deeper") {
1251                         if (!depth) {
1252                                 lex.printError("\\end_deeper: " "depth is already null");
1253                         } else {
1254                                 --depth;
1255                         }
1256                 } else {
1257                         lyxerr << "Handling unknown body token: `"
1258                                << token << '\'' << endl;
1259                 }
1260         }
1261         return true;
1262 }
1263
1264 // Returns the current font and depth as a message.
1265 docstring Text::currentState(Cursor & cur)
1266 {
1267         BOOST_ASSERT(this == cur.text());
1268         Buffer & buf = cur.buffer();
1269         Paragraph const & par = cur.paragraph();
1270         odocstringstream os;
1271
1272         if (buf.params().trackChanges)
1273                 os << _("[Change Tracking] ");
1274
1275         Change change = par.lookupChange(cur.pos());
1276
1277         if (change.type != Change::UNCHANGED) {
1278                 Author const & a = buf.params().authors().get(change.author);
1279                 os << _("Change: ") << a.name();
1280                 if (!a.email().empty())
1281                         os << " (" << a.email() << ")";
1282                 // FIXME ctime is english, we should translate that
1283                 os << _(" at ") << ctime(&change.changetime);
1284                 os << " : ";
1285         }
1286
1287         // I think we should only show changes from the default
1288         // font. (Asger)
1289         // No, from the document font (MV)
1290         Font font = cur.real_current_font;
1291         font.reduce(buf.params().getFont());
1292
1293         os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1294
1295         // The paragraph depth
1296         int depth = cur.paragraph().getDepth();
1297         if (depth > 0)
1298                 os << bformat(_(", Depth: %1$d"), depth);
1299
1300         // The paragraph spacing, but only if different from
1301         // buffer spacing.
1302         Spacing const & spacing = par.params().spacing();
1303         if (!spacing.isDefault()) {
1304                 os << _(", Spacing: ");
1305                 switch (spacing.getSpace()) {
1306                 case Spacing::Single:
1307                         os << _("Single");
1308                         break;
1309                 case Spacing::Onehalf:
1310                         os << _("OneHalf");
1311                         break;
1312                 case Spacing::Double:
1313                         os << _("Double");
1314                         break;
1315                 case Spacing::Other:
1316                         os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1317                         break;
1318                 case Spacing::Default:
1319                         // should never happen, do nothing
1320                         break;
1321                 }
1322         }
1323
1324 #ifdef DEVEL_VERSION
1325         os << _(", Inset: ") << &cur.inset();
1326         os << _(", Paragraph: ") << cur.pit();
1327         os << _(", Id: ") << par.id();
1328         os << _(", Position: ") << cur.pos();
1329         // FIXME: Why is the check for par.size() needed?
1330         // We are called with cur.pos() == par.size() quite often.
1331         if (!par.empty() && cur.pos() < par.size()) {
1332                 // Force output of code point, not character
1333                 size_t const c = par.getChar(cur.pos());
1334                 os << _(", Char: 0x") << std::hex << c;
1335         }
1336         os << _(", Boundary: ") << cur.boundary();
1337 //      Row & row = cur.textRow();
1338 //      os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
1339 #endif
1340         return os.str();
1341 }
1342
1343
1344 docstring Text::getPossibleLabel(Cursor & cur) const
1345 {
1346         pit_type pit = cur.pit();
1347
1348         LayoutPtr layout = pars_[pit].layout();
1349
1350         docstring text;
1351         docstring par_text = pars_[pit].asString(cur.buffer(), false);
1352         for (int i = 0; i < lyxrc.label_init_length; ++i) {
1353                 if (par_text.empty())
1354                         break;
1355                 docstring head;
1356                 par_text = split(par_text, head, ' ');
1357                 // Is it legal to use spaces in labels ?
1358                 if (i > 0)
1359                         text += '-';
1360                 text += head;
1361         }
1362
1363         // No need for a prefix if the user said so.
1364         if (lyxrc.label_init_length <= 0)
1365                 return text;
1366
1367         // Will contain the label type.
1368         docstring name;
1369
1370         // For section, subsection, etc...
1371         if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
1372                 LayoutPtr const & layout2 = pars_[pit - 1].layout();
1373                 if (layout2->latextype != LATEX_PARAGRAPH) {
1374                         --pit;
1375                         layout = layout2;
1376                 }
1377         }
1378         if (layout->latextype != LATEX_PARAGRAPH)
1379                 name = from_ascii(layout->latexname());
1380
1381         // for captions, we just take the caption type
1382         Inset * caption_inset = cur.innerInsetOfType(Inset::CAPTION_CODE);
1383         if (caption_inset)
1384                 name = from_ascii(static_cast<InsetCaption *>(caption_inset)->type());
1385
1386         // If none of the above worked, we'll see if we're inside various
1387         // types of insets and take our abbreviation from them.
1388         if (name.empty()) {
1389                 Inset::Code const codes[] = {
1390                         Inset::FLOAT_CODE,
1391                         Inset::WRAP_CODE,
1392                         Inset::FOOT_CODE
1393                 };
1394                 for (unsigned int i = 0; i < (sizeof codes / sizeof codes[0]); ++i) {
1395                         Inset * float_inset = cur.innerInsetOfType(codes[i]);
1396                         if (float_inset) {
1397                                 name = float_inset->name();
1398                                 break;
1399                         }
1400                 }
1401         }
1402
1403         // Create a correct prefix for prettyref
1404         if (name == "theorem")
1405                 name = from_ascii("thm");
1406         else if (name == "Foot")
1407                 name = from_ascii("fn");
1408         else if (name == "listing")
1409                 name = from_ascii("lst");
1410
1411         if (!name.empty())
1412                 text = name.substr(0, 3) + ':' + text;
1413
1414         return text;
1415 }
1416
1417
1418 void Text::charsTranspose(Cursor & cur)
1419 {
1420         BOOST_ASSERT(this == cur.text());
1421
1422         pos_type pos = cur.pos();
1423
1424         // If cursor is at beginning or end of paragraph, do nothing.
1425         if (pos == cur.lastpos() || pos == 0)
1426                 return;
1427
1428         Paragraph & par = cur.paragraph();
1429
1430         // Get the positions of the characters to be transposed.
1431         pos_type pos1 = pos - 1;
1432         pos_type pos2 = pos;
1433
1434         // In change tracking mode, ignore deleted characters.
1435         while (pos2 < cur.lastpos() && par.isDeleted(pos2))
1436                 ++pos2;
1437         if (pos2 == cur.lastpos())
1438                 return;
1439
1440         while (pos1 >= 0 && par.isDeleted(pos1))
1441                 --pos1;
1442         if (pos1 < 0)
1443                 return;
1444
1445         // Don't do anything if one of the "characters" is not regular text.
1446         if (par.isInset(pos1) || par.isInset(pos2))
1447                 return;
1448
1449         // Store the characters to be transposed (including font information).
1450         char_type char1 = par.getChar(pos1);
1451         Font const font1 =
1452                 par.getFontSettings(cur.buffer().params(), pos1);
1453
1454         char_type char2 = par.getChar(pos2);
1455         Font const font2 =
1456                 par.getFontSettings(cur.buffer().params(), pos2);
1457
1458         // And finally, we are ready to perform the transposition.
1459         // Track the changes if Change Tracking is enabled.
1460         bool const trackChanges = cur.buffer().params().trackChanges;
1461
1462         recordUndo(cur);
1463
1464         par.eraseChar(pos2, trackChanges);
1465         par.eraseChar(pos1, trackChanges);
1466         par.insertChar(pos1, char2, font2, trackChanges);
1467         par.insertChar(pos2, char1, font1, trackChanges);
1468
1469         checkBufferStructure(cur.buffer(), cur);
1470
1471         // After the transposition, move cursor to after the transposition.
1472         setCursor(cur, cur.pit(), pos2);
1473         cur.forwardPos();
1474 }
1475
1476
1477 } // namespace lyx