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