]> git.lyx.org Git - features.git/blob - src/Text.cpp
Don't save background color in Text. Hand it down at drawing time.
[features.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 void Text::breakParagraph(Cursor & cur, bool keep_layout)
360 {
361         BOOST_ASSERT(this == cur.text());
362
363         Paragraph & cpar = cur.paragraph();
364         pit_type cpit = cur.pit();
365
366         TextClass const & tclass = cur.buffer().params().getTextClass();
367         LayoutPtr const & layout = cpar.layout();
368
369         // this is only allowed, if the current paragraph is not empty
370         // or caption and if it has not the keepempty flag active
371         if (cur.lastpos() == 0 && !cpar.allowEmpty() &&
372             layout->labeltype != LABEL_SENSITIVE)
373                 return;
374
375         // a layout change may affect also the following paragraph
376         recUndo(cur, cur.pit(), undoSpan(cur.pit()) - 1);
377
378         // Always break behind a space
379         // It is better to erase the space (Dekel)
380         if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
381                 cpar.eraseChar(cur.pos(), cur.buffer().params().trackChanges);
382
383         // What should the layout for the new paragraph be?
384         int preserve_layout = 0;
385         if (keep_layout)
386                 preserve_layout = 2;
387         else
388                 preserve_layout = 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(), preserve_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         recordUndo(cur, Undo::INSERT);
442
443         Buffer const & buffer = cur.buffer();
444         Paragraph & par = cur.paragraph();
445         // try to remove this
446         pit_type const pit = cur.pit();
447
448         bool const freeSpacing = par.layout()->free_spacing ||
449                 par.isFreeSpacing();
450
451         if (lyxrc.auto_number) {
452                 static docstring const number_operators = from_ascii("+-/*");
453                 static docstring const number_unary_operators = from_ascii("+-");
454                 static docstring const number_seperators = from_ascii(".,:");
455
456                 if (cur.current_font.number() == Font::ON) {
457                         if (!isDigit(c) && !contains(number_operators, c) &&
458                             !(contains(number_seperators, c) &&
459                               cur.pos() != 0 &&
460                               cur.pos() != cur.lastpos() &&
461                               getFont(buffer, par, cur.pos()).number() == Font::ON &&
462                               getFont(buffer, par, cur.pos() - 1).number() == Font::ON)
463                            )
464                                 number(cur); // Set current_font.number to OFF
465                 } else if (isDigit(c) &&
466                            cur.real_current_font.isVisibleRightToLeft()) {
467                         number(cur); // Set current_font.number to ON
468
469                         if (cur.pos() != 0) {
470                                 char_type const c = par.getChar(cur.pos() - 1);
471                                 if (contains(number_unary_operators, c) &&
472                                     (cur.pos() == 1
473                                      || par.isSeparator(cur.pos() - 2)
474                                      || par.isNewline(cur.pos() - 2))
475                                   ) {
476                                         setCharFont(buffer, pit, cur.pos() - 1, cur.current_font);
477                                 } else if (contains(number_seperators, c)
478                                      && cur.pos() >= 2
479                                      && getFont(buffer, par, cur.pos() - 2).number() == Font::ON) {
480                                         setCharFont(buffer, pit, cur.pos() - 1, cur.current_font);
481                                 }
482                         }
483                 }
484         }
485
486         // In Bidi text, we want spaces to be treated in a special way: spaces
487         // which are between words in different languages should get the 
488         // paragraph's language; otherwise, spaces should keep the language 
489         // they were originally typed in. This is only in effect while typing;
490         // after the text is already typed in, the user can always go back and
491         // explicitly set the language of a space as desired. But 99.9% of the
492         // time, what we're doing here is what the user actually meant.
493         // 
494         // The following cases are the ones in which the language of the space
495         // should be changed to match that of the containing paragraph. In the
496         // depictions, lowercase is LTR, uppercase is RTL, underscore (_) 
497         // represents a space, pipe (|) represents the cursor position (so the
498         // character before it is the one just typed in). The different cases
499         // are depicted logically (not visually), from left to right:
500         // 
501         // 1. A_a|
502         // 2. a_A|
503         //
504         // Theoretically, there are other situations that we should, perhaps, deal
505         // with (e.g.: a|_A, A|_a). In practice, though, there really isn't any 
506         // point (to understand why, just try to create this situation...).
507
508         if ((cur.pos() >= 2) && (par.isLineSeparator(cur.pos() - 1))) {
509                 // get font in front and behind the space in question. But do NOT 
510                 // use getFont(cur.pos()) because the character c is not inserted yet
511                 Font const & pre_space_font  = getFont(buffer, par, cur.pos() - 2);
512                 Font const & post_space_font = cur.real_current_font;
513                 bool pre_space_rtl  = pre_space_font.isVisibleRightToLeft();
514                 bool post_space_rtl = post_space_font.isVisibleRightToLeft();
515                 
516                 if (pre_space_rtl != post_space_rtl) {
517                         // Set the space's language to match the language of the 
518                         // adjacent character whose direction is the paragraph's
519                         // direction; don't touch other properties of the font
520                         Language const * lang = 
521                                 (pre_space_rtl == par.isRightToLeftPar(buffer.params())) ?
522                                 pre_space_font.language() : post_space_font.language();
523
524                         Font space_font = getFont(buffer, par, cur.pos() - 1);
525                         space_font.setLanguage(lang);
526                         par.setFont(cur.pos() - 1, space_font);
527                 }
528         }
529         
530         // Next check, if there will be two blanks together or a blank at
531         // the beginning of a paragraph.
532         // I decided to handle blanks like normal characters, the main
533         // difference are the special checks when calculating the row.fill
534         // (blank does not count at the end of a row) and the check here
535
536         // When the free-spacing option is set for the current layout,
537         // disable the double-space checking
538         if (!freeSpacing && isLineSeparatorChar(c)) {
539                 if (cur.pos() == 0) {
540                         static bool sent_space_message = false;
541                         if (!sent_space_message) {
542                                 cur.message(_("You cannot insert a space at the "
543                                                            "beginning of a paragraph. Please read the Tutorial."));
544                                 sent_space_message = true;
545                         }
546                         return;
547                 }
548                 BOOST_ASSERT(cur.pos() > 0);
549                 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
550                     && !par.isDeleted(cur.pos() - 1)) {
551                         static bool sent_space_message = false;
552                         if (!sent_space_message) {
553                                 cur.message(_("You cannot type two spaces this way. "
554                                                            "Please read the Tutorial."));
555                                 sent_space_message = true;
556                         }
557                         return;
558                 }
559         }
560
561         par.insertChar(cur.pos(), c, cur.current_font, cur.buffer().params().trackChanges);
562         checkBufferStructure(cur.buffer(), cur);
563
564 //              cur.updateFlags(Update::Force);
565         setCursor(cur.top(), cur.pit(), cur.pos() + 1);
566         charInserted();
567 }
568
569
570 void Text::charInserted()
571 {
572         // Here we call finishUndo for every 20 characters inserted.
573         // This is from my experience how emacs does it. (Lgb)
574         static unsigned int counter;
575         if (counter < 20) {
576                 ++counter;
577         } else {
578                 finishUndo();
579                 counter = 0;
580         }
581 }
582
583
584 // the cursor set functions have a special mechanism. When they
585 // realize, that you left an empty paragraph, they will delete it.
586
587 bool Text::cursorRightOneWord(Cursor & cur)
588 {
589         BOOST_ASSERT(this == cur.text());
590
591         Cursor old = cur;
592
593         if (old.pos() == old.lastpos() && old.pit() != old.lastpit()) {
594                 ++old.pit();
595                 old.pos() = 0;
596         } else {
597                 // Advance through word.
598                 while (old.pos() != old.lastpos() && old.paragraph().isLetter(old.pos()))
599                         ++old.pos();
600                 // Skip through trailing nonword stuff.
601                 while (old.pos() != old.lastpos() && !old.paragraph().isLetter(old.pos()))
602                         ++old.pos();
603         }
604         return setCursor(cur, old.pit(), old.pos());
605 }
606
607
608 bool Text::cursorLeftOneWord(Cursor & cur)
609 {
610         BOOST_ASSERT(this == cur.text());
611
612         Cursor old = cur;
613
614         if (old.pos() == 0 && old.pit() != 0) {
615                 --old.pit();
616                 old.pos() = old.lastpos();
617         } else {
618                 // Skip through initial nonword stuff.
619                 while (old.pos() != 0 && !old.paragraph().isLetter(old.pos() - 1))
620                         --old.pos();
621                 // Advance through word.
622                 while (old.pos() != 0 && old.paragraph().isLetter(old.pos() - 1))
623                         --old.pos();
624         }
625         return setCursor(cur, old.pit(), old.pos());
626 }
627
628
629 void Text::selectWord(Cursor & cur, word_location loc)
630 {
631         BOOST_ASSERT(this == cur.text());
632         CursorSlice from = cur.top();
633         CursorSlice to = cur.top();
634         getWord(from, to, loc);
635         if (cur.top() != from)
636                 setCursor(cur, from.pit(), from.pos());
637         if (to == from)
638                 return;
639         cur.resetAnchor();
640         setCursor(cur, to.pit(), to.pos());
641         cur.setSelection();
642 }
643
644
645 // Select the word currently under the cursor when no
646 // selection is currently set
647 bool Text::selectWordWhenUnderCursor(Cursor & cur, word_location loc)
648 {
649         BOOST_ASSERT(this == cur.text());
650         if (cur.selection())
651                 return false;
652         selectWord(cur, loc);
653         return cur.selection();
654 }
655
656
657 void Text::acceptOrRejectChanges(Cursor & cur, ChangeOp op)
658 {
659         BOOST_ASSERT(this == cur.text());
660
661         if (!cur.selection())
662                 return;
663
664         recordUndoSelection(cur, Undo::ATOMIC);
665
666         pit_type begPit = cur.selectionBegin().pit();
667         pit_type endPit = cur.selectionEnd().pit();
668
669         pos_type begPos = cur.selectionBegin().pos();
670         pos_type endPos = cur.selectionEnd().pos();
671
672         // keep selection info, because endPos becomes invalid after the first loop
673         bool endsBeforeEndOfPar = (endPos < pars_[endPit].size());
674
675         // first, accept/reject changes within each individual paragraph (do not consider end-of-par)
676
677         for (pit_type pit = begPit; pit <= endPit; ++pit) {
678                 pos_type parSize = pars_[pit].size();
679
680                 // ignore empty paragraphs; otherwise, an assertion will fail for
681                 // acceptChanges(bparams, 0, 0) or rejectChanges(bparams, 0, 0)
682                 if (parSize == 0)
683                         continue;
684
685                 // do not consider first paragraph if the cursor starts at pos size()
686                 if (pit == begPit && begPos == parSize)
687                         continue;
688
689                 // do not consider last paragraph if the cursor ends at pos 0
690                 if (pit == endPit && endPos == 0)
691                         break; // last iteration anyway
692
693                 pos_type left  = (pit == begPit ? begPos : 0);
694                 pos_type right = (pit == endPit ? endPos : parSize);
695
696                 if (op == ACCEPT) {
697                         pars_[pit].acceptChanges(cur.buffer().params(), left, right);
698                 } else {
699                         pars_[pit].rejectChanges(cur.buffer().params(), left, right);
700                 }
701         }
702
703         // next, accept/reject imaginary end-of-par characters
704
705         for (pit_type pit = begPit; pit <= endPit; ++pit) {
706                 pos_type pos = pars_[pit].size();
707
708                 // skip if the selection ends before the end-of-par
709                 if (pit == endPit && endsBeforeEndOfPar)
710                         break; // last iteration anyway
711
712                 // skip if this is not the last paragraph of the document
713                 // note: the user should be able to accept/reject the par break of the last par!
714                 if (pit == endPit && pit + 1 != int(pars_.size()))
715                         break; // last iteration anway
716
717                 if (op == ACCEPT) {
718                         if (pars_[pit].isInserted(pos)) {
719                                 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
720                         } else if (pars_[pit].isDeleted(pos)) {
721                                 if (pit + 1 == int(pars_.size())) {
722                                         // we cannot remove a par break at the end of the last paragraph;
723                                         // instead, we mark it unchanged
724                                         pars_[pit].setChange(pos, Change(Change::UNCHANGED));
725                                 } else {
726                                         mergeParagraph(cur.buffer().params(), pars_, pit);
727                                         --endPit;
728                                         --pit;
729                                 }
730                         }
731                 } else {
732                         if (pars_[pit].isDeleted(pos)) {
733                                 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
734                         } else if (pars_[pit].isInserted(pos)) {
735                                 if (pit + 1 == int(pars_.size())) {
736                                         // we mark the par break at the end of the last paragraph unchanged
737                                         pars_[pit].setChange(pos, Change(Change::UNCHANGED));
738                                 } else {
739                                         mergeParagraph(cur.buffer().params(), pars_, pit);
740                                         --endPit;
741                                         --pit;
742                                 }
743                         }
744                 }
745         }
746
747         // finally, invoke the DEPM
748
749         deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer().params().trackChanges);
750
751         //
752
753         finishUndo();
754         cur.clearSelection();
755         setCursorIntern(cur, begPit, begPos);
756         cur.updateFlags(Update::Force);
757         updateLabels(cur.buffer());
758 }
759
760
761 void Text::acceptChanges(BufferParams const & bparams)
762 {
763         lyx::acceptChanges(pars_, bparams);
764         deleteEmptyParagraphMechanism(0, pars_.size() - 1, bparams.trackChanges);
765 }
766
767
768 void Text::rejectChanges(BufferParams const & bparams)
769 {
770         pit_type pars_size = static_cast<pit_type>(pars_.size());
771
772         // first, reject changes within each individual paragraph
773         // (do not consider end-of-par)
774         for (pit_type pit = 0; pit < pars_size; ++pit) {
775                 if (!pars_[pit].empty())   // prevent assertion failure
776                         pars_[pit].rejectChanges(bparams, 0, pars_[pit].size());
777         }
778
779         // next, reject imaginary end-of-par characters
780         for (pit_type pit = 0; pit < pars_size; ++pit) {
781                 pos_type pos = pars_[pit].size();
782
783                 if (pars_[pit].isDeleted(pos)) {
784                         pars_[pit].setChange(pos, Change(Change::UNCHANGED));
785                 } else if (pars_[pit].isInserted(pos)) {
786                         if (pit == pars_size - 1) {
787                                 // we mark the par break at the end of the last
788                                 // paragraph unchanged
789                                 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
790                         } else {
791                                 mergeParagraph(bparams, pars_, pit);
792                                 --pit;
793                                 --pars_size;
794                         }
795                 }
796         }
797
798         // finally, invoke the DEPM
799         deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.trackChanges);
800 }
801
802
803 void Text::deleteWordForward(Cursor & cur)
804 {
805         BOOST_ASSERT(this == cur.text());
806         if (cur.lastpos() == 0)
807                 cursorRight(cur);
808         else {
809                 cur.resetAnchor();
810                 cur.selection() = true;
811                 cursorRightOneWord(cur);
812                 cur.setSelection();
813                 cutSelection(cur, true, false);
814                 checkBufferStructure(cur.buffer(), cur);
815         }
816 }
817
818
819 void Text::deleteWordBackward(Cursor & cur)
820 {
821         BOOST_ASSERT(this == cur.text());
822         if (cur.lastpos() == 0)
823                 cursorLeft(cur);
824         else {
825                 cur.resetAnchor();
826                 cur.selection() = true;
827                 cursorLeftOneWord(cur);
828                 cur.setSelection();
829                 cutSelection(cur, true, false);
830                 checkBufferStructure(cur.buffer(), cur);
831         }
832 }
833
834
835 // Kill to end of line.
836 void Text::changeCase(Cursor & cur, Text::TextCase action)
837 {
838         BOOST_ASSERT(this == cur.text());
839         CursorSlice from;
840         CursorSlice to;
841
842         if (cur.selection()) {
843                 from = cur.selBegin();
844                 to = cur.selEnd();
845         } else {
846                 from = cur.top();
847                 getWord(from, to, PARTIAL_WORD);
848                 cursorRightOneWord(cur);
849         }
850
851         recordUndoSelection(cur, Undo::ATOMIC);
852
853         pit_type begPit = from.pit();
854         pit_type endPit = to.pit();
855
856         pos_type begPos = from.pos();
857         pos_type endPos = to.pos();
858
859         bool const trackChanges = cur.buffer().params().trackChanges;
860
861         pos_type right = 0; // needed after the for loop
862
863         for (pit_type pit = begPit; pit <= endPit; ++pit) {
864                 pos_type parSize = pars_[pit].size();
865
866                 pos_type pos = (pit == begPit ? begPos : 0);
867                 right = (pit == endPit ? endPos : parSize);
868
869                 // process sequences of modified characters; in change
870                 // tracking mode, this approach results in much better
871                 // usability than changing case on a char-by-char basis
872                 docstring changes;
873
874                 bool capitalize = true;
875
876                 for (; pos < right; ++pos) {
877                         char_type oldChar = pars_[pit].getChar(pos);
878                         char_type newChar = oldChar;
879
880                         // ignore insets and don't play with deleted text!
881                         if (oldChar != Paragraph::META_INSET && !pars_[pit].isDeleted(pos)) {
882                                 switch (action) {
883                                 case text_lowercase:
884                                         newChar = lowercase(oldChar);
885                                         break;
886                                 case text_capitalization:
887                                         if (capitalize) {
888                                                 newChar = uppercase(oldChar);
889                                                 capitalize = false;
890                                         }
891                                         break;
892                                 case text_uppercase:
893                                         newChar = uppercase(oldChar);
894                                         break;
895                                 }
896                         }
897
898                         if (!pars_[pit].isLetter(pos) || pars_[pit].isDeleted(pos)) {
899                                 capitalize = true; // permit capitalization again
900                         }
901
902                         if (oldChar != newChar) {
903                                 changes += newChar;
904                         }
905
906                         if (oldChar == newChar || pos == right - 1) {
907                                 if (oldChar != newChar) {
908                                         pos++; // step behind the changing area
909                                 }
910                                 int erasePos = pos - changes.size();
911                                 for (size_t i = 0; i < changes.size(); i++) {
912                                         pars_[pit].insertChar(pos, changes[i],
913                                                 pars_[pit].getFontSettings(cur.buffer().params(),
914                                                                 erasePos),
915                                                 trackChanges);
916                                         if (!pars_[pit].eraseChar(erasePos, trackChanges)) {
917                                                 ++erasePos;
918                                                 ++pos; // advance
919                                                 ++right; // expand selection
920                                         }
921                                 }
922                                 changes.clear();
923                         }
924                 }
925         }
926
927         // the selection may have changed due to logically-only deleted chars
928         setCursor(cur, begPit, begPos);
929         cur.resetAnchor();
930         setCursor(cur, endPit, right);
931         cur.setSelection();
932
933         checkBufferStructure(cur.buffer(), cur);
934 }
935
936
937 bool Text::handleBibitems(Cursor & cur)
938 {
939         if (cur.paragraph().layout()->labeltype != LABEL_BIBLIO)
940                 return false;
941         // if a bibitem is deleted, merge with previous paragraph
942         // if this is a bibliography item as well
943         if (cur.pos() == 0) {
944                 BufferParams const & bufparams = cur.buffer().params();
945                 Paragraph const & par = cur.paragraph();
946                 Cursor prevcur = cur;
947                 if (cur.pit() > 0) {
948                         --prevcur.pit();
949                         prevcur.pos() = prevcur.lastpos();
950                 }
951                 Paragraph const & prevpar = prevcur.paragraph();
952                 if (cur.pit() > 0 && par.layout() == prevpar.layout()) {
953                         recordUndo(cur, Undo::ATOMIC, prevcur.pit());
954                         mergeParagraph(bufparams, cur.text()->paragraphs(),
955                                        prevcur.pit());
956                         updateLabels(cur.buffer());
957                         setCursorIntern(cur, prevcur.pit(), prevcur.pos());
958                         cur.updateFlags(Update::Force);
959                 // if not, reset the paragraph to default
960                 } else
961                         cur.paragraph().layout(
962                                 bufparams.getTextClass().defaultLayout());
963                 return true;
964         }
965         return false;
966 }
967
968
969 bool Text::erase(Cursor & cur)
970 {
971         BOOST_ASSERT(this == cur.text());
972         bool needsUpdate = false;
973         Paragraph & par = cur.paragraph();
974
975         if (cur.pos() != cur.lastpos()) {
976                 // this is the code for a normal delete, not pasting
977                 // any paragraphs
978                 recordUndo(cur, Undo::DELETE);
979                 if(!par.eraseChar(cur.pos(), cur.buffer().params().trackChanges)) {
980                         // the character has been logically deleted only => skip it
981                         cur.top().forwardPos();
982                 }
983                 checkBufferStructure(cur.buffer(), cur);
984                 needsUpdate = true;
985         } else {
986                 if (cur.pit() == cur.lastpit())
987                         return dissolveInset(cur);
988
989                 if (!par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
990                         par.setChange(cur.pos(), Change(Change::DELETED));
991                         cur.forwardPos();
992                         needsUpdate = true;
993                 } else {
994                         setCursorIntern(cur, cur.pit() + 1, 0);
995                         needsUpdate = backspacePos0(cur);
996                 }
997         }
998
999         needsUpdate |= handleBibitems(cur);
1000
1001         if (needsUpdate) {
1002                 // Make sure the cursor is correct. Is this really needed?
1003                 // No, not really... at least not here!
1004                 cur.text()->setCursor(cur.top(), cur.pit(), cur.pos());
1005                 checkBufferStructure(cur.buffer(), cur);
1006         }
1007
1008         return needsUpdate;
1009 }
1010
1011
1012 bool Text::backspacePos0(Cursor & cur)
1013 {
1014         BOOST_ASSERT(this == cur.text());
1015         if (cur.pit() == 0)
1016                 return false;
1017
1018         bool needsUpdate = false;
1019
1020         BufferParams const & bufparams = cur.buffer().params();
1021         TextClass const & tclass = bufparams.getTextClass();
1022         ParagraphList & plist = cur.text()->paragraphs();
1023         Paragraph const & par = cur.paragraph();
1024         Cursor prevcur = cur;
1025         --prevcur.pit();
1026         prevcur.pos() = prevcur.lastpos();
1027         Paragraph const & prevpar = prevcur.paragraph();
1028
1029         // is it an empty paragraph?
1030         if (cur.lastpos() == 0
1031             || (cur.lastpos() == 1 && par.isSeparator(0))) {
1032                 recordUndo(cur, Undo::ATOMIC, prevcur.pit(), cur.pit());
1033                 plist.erase(boost::next(plist.begin(), cur.pit()));
1034                 needsUpdate = true;
1035         }
1036         // is previous par empty?
1037         else if (prevcur.lastpos() == 0
1038                  || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
1039                 recordUndo(cur, Undo::ATOMIC, prevcur.pit(), cur.pit());
1040                 plist.erase(boost::next(plist.begin(), prevcur.pit()));
1041                 needsUpdate = true;
1042         }
1043         // Pasting is not allowed, if the paragraphs have different
1044         // layouts. I think it is a real bug of all other
1045         // word processors to allow it. It confuses the user.
1046         // Correction: Pasting is always allowed with standard-layout
1047         else if (par.layout() == prevpar.layout()
1048                  || par.layout() == tclass.defaultLayout()) {
1049                 recordUndo(cur, Undo::ATOMIC, prevcur.pit());
1050                 mergeParagraph(bufparams, plist, prevcur.pit());
1051                 needsUpdate = true;
1052         }
1053
1054         if (needsUpdate) {
1055                 updateLabels(cur.buffer());
1056                 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1057         }
1058
1059         return needsUpdate;
1060 }
1061
1062
1063 bool Text::backspace(Cursor & cur)
1064 {
1065         BOOST_ASSERT(this == cur.text());
1066         bool needsUpdate = false;
1067         if (cur.pos() == 0) {
1068                 if (cur.pit() == 0)
1069                         return dissolveInset(cur);
1070
1071                 Paragraph & prev_par = pars_[cur.pit() - 1];
1072
1073                 if (!prev_par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
1074                         prev_par.setChange(prev_par.size(), Change(Change::DELETED));
1075                         setCursorIntern(cur, cur.pit() - 1, prev_par.size());
1076                         return true;
1077                 }
1078                 // The cursor is at the beginning of a paragraph, so
1079                 // the backspace will collapse two paragraphs into one.
1080                 needsUpdate = backspacePos0(cur);
1081
1082         } else {
1083                 // this is the code for a normal backspace, not pasting
1084                 // any paragraphs
1085                 recordUndo(cur, Undo::DELETE);
1086                 // We used to do cursorLeftIntern() here, but it is
1087                 // not a good idea since it triggers the auto-delete
1088                 // mechanism. So we do a cursorLeftIntern()-lite,
1089                 // without the dreaded mechanism. (JMarc)
1090                 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1091                                 false, cur.boundary());
1092                 cur.paragraph().eraseChar(cur.pos(), cur.buffer().params().trackChanges);
1093                 checkBufferStructure(cur.buffer(), cur);
1094         }
1095
1096         if (cur.pos() == cur.lastpos())
1097                 cur.setCurrentFont();
1098
1099         needsUpdate |= handleBibitems(cur);
1100
1101         // A singlePar update is not enough in this case.
1102 //              cur.updateFlags(Update::Force);
1103         setCursor(cur.top(), cur.pit(), cur.pos());
1104
1105         return needsUpdate;
1106 }
1107
1108
1109 bool Text::dissolveInset(Cursor & cur) {
1110         BOOST_ASSERT(this == cur.text());
1111
1112         if (isMainText(cur.bv().buffer()) || cur.inset().nargs() != 1)
1113                 return false;
1114
1115         recordUndoInset(cur);
1116         cur.selHandle(false);
1117         // save position
1118         pos_type spos = cur.pos();
1119         pit_type spit = cur.pit();
1120         ParagraphList plist;
1121         if (cur.lastpit() != 0 || cur.lastpos() != 0)
1122                 plist = paragraphs();
1123         cur.popLeft();
1124         // store cursor offset
1125         if (spit == 0)
1126                 spos += cur.pos();
1127         spit += cur.pit();
1128         Buffer & b = cur.buffer();
1129         cur.paragraph().eraseChar(cur.pos(), b.params().trackChanges);
1130         if (!plist.empty()) {
1131                 // ERT paragraphs have the Language latex_language.
1132                 // This is invalid outside of ERT, so we need to
1133                 // change it to the buffer language.
1134                 ParagraphList::iterator it = plist.begin();
1135                 ParagraphList::iterator it_end = plist.end();
1136                 for (; it != it_end; it++) {
1137                         it->changeLanguage(b.params(), latex_language,
1138                                         b.getLanguage());
1139                 }
1140
1141                 pasteParagraphList(cur, plist, b.params().getTextClass_ptr(),
1142                                    b.errorList("Paste"));
1143                 // restore position
1144                 cur.pit() = std::min(cur.lastpit(), spit);
1145                 cur.pos() = std::min(cur.lastpos(), spos);
1146         }
1147         cur.clearSelection();
1148         cur.resetAnchor();
1149         return true;
1150 }
1151
1152
1153 void Text::getWord(CursorSlice & from, CursorSlice & to,
1154         word_location const loc)
1155 {
1156         Paragraph const & from_par = pars_[from.pit()];
1157         switch (loc) {
1158         case WHOLE_WORD_STRICT:
1159                 if (from.pos() == 0 || from.pos() == from_par.size()
1160                     || !from_par.isLetter(from.pos())
1161                     || !from_par.isLetter(from.pos() - 1)) {
1162                         to = from;
1163                         return;
1164                 }
1165                 // no break here, we go to the next
1166
1167         case WHOLE_WORD:
1168                 // If we are already at the beginning of a word, do nothing
1169                 if (!from.pos() || !from_par.isLetter(from.pos() - 1))
1170                         break;
1171                 // no break here, we go to the next
1172
1173         case PREVIOUS_WORD:
1174                 // always move the cursor to the beginning of previous word
1175                 while (from.pos() && from_par.isLetter(from.pos() - 1))
1176                         --from.pos();
1177                 break;
1178         case NEXT_WORD:
1179                 lyxerr << "Text::getWord: NEXT_WORD not implemented yet"
1180                        << endl;
1181                 break;
1182         case PARTIAL_WORD:
1183                 // no need to move the 'from' cursor
1184                 break;
1185         }
1186         to = from;
1187         Paragraph & to_par = pars_[to.pit()];
1188         while (to.pos() < to_par.size() && to_par.isLetter(to.pos()))
1189                 ++to.pos();
1190 }
1191
1192
1193 void Text::write(Buffer const & buf, std::ostream & os) const
1194 {
1195         ParagraphList::const_iterator pit = paragraphs().begin();
1196         ParagraphList::const_iterator end = paragraphs().end();
1197         depth_type dth = 0;
1198         for (; pit != end; ++pit)
1199                 pit->write(buf, os, buf.params(), dth);
1200
1201         // Close begin_deeper
1202         for(; dth > 0; --dth)
1203                 os << "\n\\end_deeper";
1204 }
1205
1206
1207 bool Text::read(Buffer const & buf, Lexer & lex, ErrorList & errorList)
1208 {
1209         depth_type depth = 0;
1210
1211         while (lex.isOK()) {
1212                 lex.nextToken();
1213                 string const token = lex.getString();
1214
1215                 if (token.empty())
1216                         continue;
1217
1218                 if (token == "\\end_inset")
1219                         break;
1220
1221                 if (token == "\\end_body")
1222                         continue;
1223
1224                 if (token == "\\begin_body")
1225                         continue;
1226
1227                 if (token == "\\end_document")
1228                         return false;
1229
1230                 if (token == "\\begin_layout") {
1231                         lex.pushToken(token);
1232
1233                         Paragraph par;
1234                         par.params().depth(depth);
1235                         par.setFont(0, Font(Font::ALL_INHERIT, buf.params().language));
1236                         pars_.push_back(par);
1237
1238                         // FIXME: goddamn InsetTabular makes us pass a Buffer
1239                         // not BufferParams
1240                         lyx::readParagraph(buf, pars_.back(), lex, errorList);
1241
1242                 } else if (token == "\\begin_deeper") {
1243                         ++depth;
1244                 } else if (token == "\\end_deeper") {
1245                         if (!depth) {
1246                                 lex.printError("\\end_deeper: " "depth is already null");
1247                         } else {
1248                                 --depth;
1249                         }
1250                 } else {
1251                         lyxerr << "Handling unknown body token: `"
1252                                << token << '\'' << endl;
1253                 }
1254         }
1255         return true;
1256 }
1257
1258 // Returns the current font and depth as a message.
1259 docstring Text::currentState(Cursor & cur)
1260 {
1261         BOOST_ASSERT(this == cur.text());
1262         Buffer & buf = cur.buffer();
1263         Paragraph const & par = cur.paragraph();
1264         odocstringstream os;
1265
1266         if (buf.params().trackChanges)
1267                 os << _("[Change Tracking] ");
1268
1269         Change change = par.lookupChange(cur.pos());
1270
1271         if (change.type != Change::UNCHANGED) {
1272                 Author const & a = buf.params().authors().get(change.author);
1273                 os << _("Change: ") << a.name();
1274                 if (!a.email().empty())
1275                         os << " (" << a.email() << ")";
1276                 // FIXME ctime is english, we should translate that
1277                 os << _(" at ") << ctime(&change.changetime);
1278                 os << " : ";
1279         }
1280
1281         // I think we should only show changes from the default
1282         // font. (Asger)
1283         // No, from the document font (MV)
1284         Font font = cur.real_current_font;
1285         font.reduce(buf.params().getFont());
1286
1287         os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1288
1289         // The paragraph depth
1290         int depth = cur.paragraph().getDepth();
1291         if (depth > 0)
1292                 os << bformat(_(", Depth: %1$d"), depth);
1293
1294         // The paragraph spacing, but only if different from
1295         // buffer spacing.
1296         Spacing const & spacing = par.params().spacing();
1297         if (!spacing.isDefault()) {
1298                 os << _(", Spacing: ");
1299                 switch (spacing.getSpace()) {
1300                 case Spacing::Single:
1301                         os << _("Single");
1302                         break;
1303                 case Spacing::Onehalf:
1304                         os << _("OneHalf");
1305                         break;
1306                 case Spacing::Double:
1307                         os << _("Double");
1308                         break;
1309                 case Spacing::Other:
1310                         os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1311                         break;
1312                 case Spacing::Default:
1313                         // should never happen, do nothing
1314                         break;
1315                 }
1316         }
1317
1318 #ifdef DEVEL_VERSION
1319         os << _(", Inset: ") << &cur.inset();
1320         os << _(", Paragraph: ") << cur.pit();
1321         os << _(", Id: ") << par.id();
1322         os << _(", Position: ") << cur.pos();
1323         // FIXME: Why is the check for par.size() needed?
1324         // We are called with cur.pos() == par.size() quite often.
1325         if (!par.empty() && cur.pos() < par.size()) {
1326                 // Force output of code point, not character
1327                 size_t const c = par.getChar(cur.pos());
1328                 os << _(", Char: 0x") << std::hex << c;
1329         }
1330         os << _(", Boundary: ") << cur.boundary();
1331 //      Row & row = cur.textRow();
1332 //      os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
1333 #endif
1334         return os.str();
1335 }
1336
1337
1338 docstring Text::getPossibleLabel(Cursor & cur) const
1339 {
1340         pit_type pit = cur.pit();
1341
1342         LayoutPtr layout = pars_[pit].layout();
1343
1344         docstring text;
1345         docstring par_text = pars_[pit].asString(cur.buffer(), false);
1346         for (int i = 0; i < lyxrc.label_init_length; ++i) {
1347                 if (par_text.empty())
1348                         break;
1349                 docstring head;
1350                 par_text = split(par_text, head, ' ');
1351                 // Is it legal to use spaces in labels ?
1352                 if (i > 0)
1353                         text += '-';
1354                 text += head;
1355         }
1356
1357         // No need for a prefix if the user said so.
1358         if (lyxrc.label_init_length <= 0)
1359                 return text;
1360
1361         // Will contain the label type.
1362         docstring name;
1363
1364         // For section, subsection, etc...
1365         if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
1366                 LayoutPtr const & layout2 = pars_[pit - 1].layout();
1367                 if (layout2->latextype != LATEX_PARAGRAPH) {
1368                         --pit;
1369                         layout = layout2;
1370                 }
1371         }
1372         if (layout->latextype != LATEX_PARAGRAPH)
1373                 name = from_ascii(layout->latexname());
1374
1375         // for captions, we just take the caption type
1376         Inset * caption_inset = cur.innerInsetOfType(Inset::CAPTION_CODE);
1377         if (caption_inset)
1378                 name = from_ascii(static_cast<InsetCaption *>(caption_inset)->type());
1379
1380         // If none of the above worked, we'll see if we're inside various
1381         // types of insets and take our abbreviation from them.
1382         if (name.empty()) {
1383                 Inset::Code const codes[] = {
1384                         Inset::FLOAT_CODE,
1385                         Inset::WRAP_CODE,
1386                         Inset::FOOT_CODE
1387                 };
1388                 for (unsigned int i = 0; i < (sizeof codes / sizeof codes[0]); ++i) {
1389                         Inset * float_inset = cur.innerInsetOfType(codes[i]);
1390                         if (float_inset) {
1391                                 name = float_inset->name();
1392                                 break;
1393                         }
1394                 }
1395         }
1396
1397         // Create a correct prefix for prettyref
1398         if (name == "theorem")
1399                 name = from_ascii("thm");
1400         else if (name == "Foot")
1401                 name = from_ascii("fn");
1402         else if (name == "listing")
1403                 name = from_ascii("lst");
1404
1405         if (!name.empty())
1406                 text = name.substr(0, 3) + ':' + text;
1407
1408         return text;
1409 }
1410
1411
1412 void Text::charsTranspose(Cursor & cur)
1413 {
1414         BOOST_ASSERT(this == cur.text());
1415
1416         pos_type pos = cur.pos();
1417
1418         // If cursor is at beginning or end of paragraph, do nothing.
1419         if (pos == cur.lastpos() || pos == 0)
1420                 return;
1421
1422         Paragraph & par = cur.paragraph();
1423
1424         // Get the positions of the characters to be transposed.
1425         pos_type pos1 = pos - 1;
1426         pos_type pos2 = pos;
1427
1428         // In change tracking mode, ignore deleted characters.
1429         while (pos2 < cur.lastpos() && par.isDeleted(pos2))
1430                 ++pos2;
1431         if (pos2 == cur.lastpos())
1432                 return;
1433
1434         while (pos1 >= 0 && par.isDeleted(pos1))
1435                 --pos1;
1436         if (pos1 < 0)
1437                 return;
1438
1439         // Don't do anything if one of the "characters" is not regular text.
1440         if (par.isInset(pos1) || par.isInset(pos2))
1441                 return;
1442
1443         // Store the characters to be transposed (including font information).
1444         char_type char1 = par.getChar(pos1);
1445         Font const font1 =
1446                 par.getFontSettings(cur.buffer().params(), pos1);
1447
1448         char_type char2 = par.getChar(pos2);
1449         Font const font2 =
1450                 par.getFontSettings(cur.buffer().params(), pos2);
1451
1452         // And finally, we are ready to perform the transposition.
1453         // Track the changes if Change Tracking is enabled.
1454         bool const trackChanges = cur.buffer().params().trackChanges;
1455
1456         recordUndo(cur);
1457
1458         par.eraseChar(pos2, trackChanges);
1459         par.eraseChar(pos1, trackChanges);
1460         par.insertChar(pos1, char2, font2, trackChanges);
1461         par.insertChar(pos2, char1, font1, trackChanges);
1462
1463         checkBufferStructure(cur.buffer(), cur);
1464
1465         // After the transposition, move cursor to after the transposition.
1466         setCursor(cur, cur.pit(), pos2);
1467         cur.forwardPos();
1468 }
1469
1470
1471 } // namespace lyx