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