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