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