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