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