3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Asger Alstrup
7 * \author Lars Gullik Bjønnes
8 * \author Dov Feldstern
9 * \author Jean-Marc Lasgouttes
11 * \author André Pönitz
12 * \author Stefan Schimanski
14 * \author Jürgen Vigna
16 * Full author contact details are available in file CREDITS.
25 #include "buffer_funcs.h"
26 #include "BufferParams.h"
27 #include "BufferView.h"
28 #include "bufferview_funcs.h"
30 #include "ParIterator.h"
31 #include "CoordCache.h"
32 #include "CutAndPaste.h"
34 #include "DispatchResult.h"
36 #include "ErrorList.h"
37 #include "FuncRequest.h"
39 #include "FontIterator.h"
47 #include "MetricsInfo.h"
48 #include "Paragraph.h"
49 #include "paragraph_funcs.h"
50 #include "ParagraphParameters.h"
53 #include "WordLangTuple.h"
55 #include "frontends/FontMetrics.h"
56 #include "frontends/Painter.h"
58 #include "insets/InsetText.h"
59 #include "insets/InsetBibitem.h"
60 #include "insets/InsetCaption.h"
61 #include "insets/InsetHFill.h"
62 #include "insets/InsetLine.h"
63 #include "insets/InsetNewline.h"
64 #include "insets/InsetPagebreak.h"
65 #include "insets/InsetOptArg.h"
66 #include "insets/InsetSpace.h"
67 #include "insets/InsetSpecialChar.h"
68 #include "insets/InsetTabular.h"
70 #include "support/lstrings.h"
71 #include "support/textutils.h"
72 #include "support/convert.h"
74 #include <boost/current_function.hpp>
88 using support::bformat;
89 using support::contains;
90 using support::lowercase;
92 using support::uppercase;
94 using cap::cutSelection;
95 using cap::pasteParagraphList;
97 using frontend::FontMetrics;
101 void readParToken(Buffer const & buf, Paragraph & par, Lexer & lex,
102 string const & token, Font & font, Change & change, ErrorList & errorList)
104 BufferParams const & bp = buf.params();
106 if (token[0] != '\\') {
108 string::const_iterator cit = token.begin();
109 for (; cit != token.end(); ++cit)
110 par.insertChar(par.size(), (*cit), font, change);
112 docstring dstr = lex.getDocString();
113 docstring::const_iterator cit = dstr.begin();
114 docstring::const_iterator cend = dstr.end();
115 for (; cit != cend; ++cit)
116 par.insertChar(par.size(), *cit, font, change);
118 } else if (token == "\\begin_layout") {
120 docstring layoutname = lex.getDocString();
122 font = Font(Font::ALL_INHERIT, bp.language);
123 change = Change(Change::UNCHANGED);
125 TextClass const & tclass = bp.getTextClass();
127 if (layoutname.empty()) {
128 layoutname = tclass.defaultLayoutName();
131 bool hasLayout = tclass.hasLayout(layoutname);
134 errorList.push_back(ErrorItem(_("Unknown layout"),
135 bformat(_("Layout '%1$s' does not exist in textclass '%2$s'\nTrying to use the default instead.\n"),
136 layoutname, from_utf8(tclass.name())), par.id(), 0, par.size()));
137 layoutname = tclass.defaultLayoutName();
140 par.layout(bp.getTextClass()[layoutname]);
142 // Test whether the layout is obsolete.
143 LayoutPtr const & layout = par.layout();
144 if (!layout->obsoleted_by().empty())
145 par.layout(bp.getTextClass()[layout->obsoleted_by()]);
147 par.params().read(lex);
149 } else if (token == "\\end_layout") {
150 lyxerr << BOOST_CURRENT_FUNCTION
151 << ": Solitary \\end_layout in line "
152 << lex.getLineNo() << "\n"
153 << "Missing \\begin_layout?.\n";
154 } else if (token == "\\end_inset") {
155 lyxerr << BOOST_CURRENT_FUNCTION
156 << ": Solitary \\end_inset in line "
157 << lex.getLineNo() << "\n"
158 << "Missing \\begin_inset?.\n";
159 } else if (token == "\\begin_inset") {
160 Inset * inset = readInset(lex, buf);
162 par.insertInset(par.size(), inset, font, change);
165 docstring line = lex.getDocString();
166 errorList.push_back(ErrorItem(_("Unknown Inset"), line,
167 par.id(), 0, par.size()));
169 } else if (token == "\\family") {
171 font.setLyXFamily(lex.getString());
172 } else if (token == "\\series") {
174 font.setLyXSeries(lex.getString());
175 } else if (token == "\\shape") {
177 font.setLyXShape(lex.getString());
178 } else if (token == "\\size") {
180 font.setLyXSize(lex.getString());
181 } else if (token == "\\lang") {
183 string const tok = lex.getString();
184 Language const * lang = languages.getLanguage(tok);
186 font.setLanguage(lang);
188 font.setLanguage(bp.language);
189 lex.printError("Unknown language `$$Token'");
191 } else if (token == "\\numeric") {
193 font.setNumber(font.setLyXMisc(lex.getString()));
194 } else if (token == "\\emph") {
196 font.setEmph(font.setLyXMisc(lex.getString()));
197 } else if (token == "\\bar") {
199 string const tok = lex.getString();
202 font.setUnderbar(Font::ON);
203 else if (tok == "no")
204 font.setUnderbar(Font::OFF);
205 else if (tok == "default")
206 font.setUnderbar(Font::INHERIT);
208 lex.printError("Unknown bar font flag "
210 } else if (token == "\\noun") {
212 font.setNoun(font.setLyXMisc(lex.getString()));
213 } else if (token == "\\color") {
215 font.setLyXColor(lex.getString());
216 } else if (token == "\\InsetSpace" || token == "\\SpecialChar") {
218 // Insets don't make sense in a free-spacing context! ---Kayvan
219 if (par.isFreeSpacing()) {
220 if (token == "\\InsetSpace")
221 par.insertChar(par.size(), ' ', font, change);
222 else if (lex.isOK()) {
224 string const next_token = lex.getString();
225 if (next_token == "\\-")
226 par.insertChar(par.size(), '-', font, change);
228 lex.printError("Token `$$Token' "
230 "paragraph layout!");
234 auto_ptr<Inset> inset;
235 if (token == "\\SpecialChar" )
236 inset.reset(new InsetSpecialChar);
238 inset.reset(new InsetSpace);
239 inset->read(buf, lex);
240 par.insertInset(par.size(), inset.release(),
243 } else if (token == "\\backslash") {
244 par.insertChar(par.size(), '\\', font, change);
245 } else if (token == "\\newline") {
246 auto_ptr<Inset> inset(new InsetNewline);
247 inset->read(buf, lex);
248 par.insertInset(par.size(), inset.release(), font, change);
249 } else if (token == "\\LyXTable") {
250 auto_ptr<Inset> inset(new InsetTabular(buf));
251 inset->read(buf, lex);
252 par.insertInset(par.size(), inset.release(), font, change);
253 } else if (token == "\\hfill") {
254 par.insertInset(par.size(), new InsetHFill, font, change);
255 } else if (token == "\\lyxline") {
256 par.insertInset(par.size(), new InsetLine, font, change);
257 } else if (token == "\\newpage") {
258 par.insertInset(par.size(), new InsetPagebreak, font, change);
259 } else if (token == "\\clearpage") {
260 par.insertInset(par.size(), new InsetClearPage, font, change);
261 } else if (token == "\\cleardoublepage") {
262 par.insertInset(par.size(), new InsetClearDoublePage, font, change);
263 } else if (token == "\\change_unchanged") {
264 change = Change(Change::UNCHANGED);
265 } else if (token == "\\change_inserted") {
267 std::istringstream is(lex.getString());
271 if (aid >= bp.author_map.size()) {
272 errorList.push_back(ErrorItem(_("Change tracking error"),
273 bformat(_("Unknown author index for insertion: %1$d\n"), aid),
274 par.id(), 0, par.size()));
275 change = Change(Change::UNCHANGED);
277 change = Change(Change::INSERTED, bp.author_map[aid], ct);
278 } else if (token == "\\change_deleted") {
280 std::istringstream is(lex.getString());
284 if (aid >= bp.author_map.size()) {
285 errorList.push_back(ErrorItem(_("Change tracking error"),
286 bformat(_("Unknown author index for deletion: %1$d\n"), aid),
287 par.id(), 0, par.size()));
288 change = Change(Change::UNCHANGED);
290 change = Change(Change::DELETED, bp.author_map[aid], ct);
293 errorList.push_back(ErrorItem(_("Unknown token"),
294 bformat(_("Unknown token: %1$s %2$s\n"), from_utf8(token),
296 par.id(), 0, par.size()));
301 void readParagraph(Buffer const & buf, Paragraph & par, Lexer & lex,
302 ErrorList & errorList)
305 string token = lex.getString();
307 Change change(Change::UNCHANGED);
310 readParToken(buf, par, lex, token, font, change, errorList);
313 token = lex.getString();
318 if (token == "\\end_layout") {
319 //Ok, paragraph finished
323 LYXERR(Debug::PARSER) << "Handling paragraph token: `"
324 << token << '\'' << endl;
325 if (token == "\\begin_layout" || token == "\\end_document"
326 || token == "\\end_inset" || token == "\\begin_deeper"
327 || token == "\\end_deeper") {
328 lex.pushToken(token);
329 lyxerr << "Paragraph ended in line "
330 << lex.getLineNo() << "\n"
331 << "Missing \\end_layout.\n";
335 // Final change goes to paragraph break:
336 par.setChange(par.size(), change);
338 // Initialize begin_of_body_ on load; redoParagraph maintains
339 par.setBeginOfBody();
346 bool Text::empty() const
348 return pars_.empty() || (pars_.size() == 1 && pars_[0].empty()
349 // FIXME: Should we consider the labeled type as empty too?
350 && pars_[0].layout()->labeltype == LABEL_NO_LABEL);
354 double Text::spacing(Buffer const & buffer,
355 Paragraph const & par) const
357 if (par.params().spacing().isDefault())
358 return buffer.params().spacing().getValue();
359 return par.params().spacing().getValue();
363 int Text::leftMargin(Buffer const & buffer, int max_width, pit_type pit) const
365 BOOST_ASSERT(pit >= 0);
366 BOOST_ASSERT(pit < int(pars_.size()));
367 return leftMargin(buffer, max_width, pit, pars_[pit].size());
371 int Text::leftMargin(Buffer const & buffer, int max_width,
372 pit_type const pit, pos_type const pos) const
374 BOOST_ASSERT(pit >= 0);
375 BOOST_ASSERT(pit < int(pars_.size()));
376 Paragraph const & par = pars_[pit];
377 BOOST_ASSERT(pos >= 0);
378 BOOST_ASSERT(pos <= par.size());
379 //lyxerr << "Text::leftMargin: pit: " << pit << " pos: " << pos << endl;
380 TextClass const & tclass = buffer.params().getTextClass();
381 LayoutPtr const & layout = par.layout();
383 docstring parindent = layout->parindent;
387 if (isMainText(buffer))
388 l_margin += changebarMargin();
390 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
391 tclass.leftmargin());
393 if (par.getDepth() != 0) {
394 // find the next level paragraph
395 pit_type newpar = outerHook(pit, pars_);
396 if (newpar != pit_type(pars_.size())) {
397 if (pars_[newpar].layout()->isEnvironment()) {
398 l_margin = leftMargin(buffer, max_width, newpar);
400 if (par.layout() == tclass.defaultLayout()) {
401 if (pars_[newpar].params().noindent())
404 parindent = pars_[newpar].layout()->parindent;
409 // This happens after sections in standard classes. The 1.3.x
410 // code compared depths too, but it does not seem necessary
412 if (par.layout() == tclass.defaultLayout()
413 && pit > 0 && pars_[pit - 1].layout()->nextnoindent)
416 Font const labelfont = getLabelFont(buffer, par);
417 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
419 switch (layout->margintype) {
421 if (!layout->leftmargin.empty()) {
422 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
425 if (!par.getLabelstring().empty()) {
426 l_margin += labelfont_metrics.signedWidth(layout->labelindent);
427 l_margin += labelfont_metrics.width(par.getLabelstring());
428 l_margin += labelfont_metrics.width(layout->labelsep);
432 case MARGIN_MANUAL: {
433 l_margin += labelfont_metrics.signedWidth(layout->labelindent);
434 // The width of an empty par, even with manual label, should be 0
435 if (!par.empty() && pos >= par.beginOfBody()) {
436 if (!par.getLabelWidthString().empty()) {
437 docstring labstr = par.getLabelWidthString();
438 l_margin += labelfont_metrics.width(labstr);
439 l_margin += labelfont_metrics.width(layout->labelsep);
445 case MARGIN_STATIC: {
446 l_margin += theFontMetrics(buffer.params().getFont()).
447 signedWidth(layout->leftmargin) * 4 / (par.getDepth() + 4);
451 case MARGIN_FIRST_DYNAMIC:
452 if (layout->labeltype == LABEL_MANUAL) {
453 if (pos >= par.beginOfBody()) {
454 l_margin += labelfont_metrics.signedWidth(layout->leftmargin);
456 l_margin += labelfont_metrics.signedWidth(layout->labelindent);
459 // Special case to fix problems with
461 || (layout->labeltype == LABEL_STATIC
462 && layout->latextype == LATEX_ENVIRONMENT
463 && !isFirstInSequence(pit, pars_))) {
464 l_margin += labelfont_metrics.signedWidth(layout->leftmargin);
465 } else if (layout->labeltype != LABEL_TOP_ENVIRONMENT
466 && layout->labeltype != LABEL_BIBLIO
467 && layout->labeltype !=
468 LABEL_CENTERED_TOP_ENVIRONMENT) {
469 l_margin += labelfont_metrics.signedWidth(layout->labelindent);
470 l_margin += labelfont_metrics.width(layout->labelsep);
471 l_margin += labelfont_metrics.width(par.getLabelstring());
475 case MARGIN_RIGHT_ADDRESS_BOX: {
477 // ok, a terrible hack. The left margin depends on the widest
478 // row in this paragraph.
479 RowList::iterator rit = par.rows().begin();
480 RowList::iterator end = par.rows().end();
481 // FIXME: This is wrong.
482 int minfill = max_width;
483 for ( ; rit != end; ++rit)
484 if (rit->fill() < minfill)
485 minfill = rit->fill();
486 l_margin += theFontMetrics(params.getFont()).signedWidth(layout->leftmargin);
489 // also wrong, but much shorter.
490 l_margin += max_width / 2;
495 if (!par.params().leftIndent().zero())
496 l_margin += par.params().leftIndent().inPixels(max_width);
500 if (par.params().align() == LYX_ALIGN_LAYOUT)
501 align = layout->align;
503 align = par.params().align();
505 // set the correct parindent
507 && (layout->labeltype == LABEL_NO_LABEL
508 || layout->labeltype == LABEL_TOP_ENVIRONMENT
509 || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
510 || (layout->labeltype == LABEL_STATIC
511 && layout->latextype == LATEX_ENVIRONMENT
512 && !isFirstInSequence(pit, pars_)))
513 && align == LYX_ALIGN_BLOCK
514 && !par.params().noindent()
515 // in some insets, paragraphs are never indented
516 && !(par.inInset() && par.inInset()->neverIndent(buffer))
517 // display style insets are always centered, omit indentation
520 && par.getInset(pos)->display())
521 && (par.layout() != tclass.defaultLayout()
522 || buffer.params().paragraph_separation ==
523 BufferParams::PARSEP_INDENT))
525 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
533 Color_color Text::backgroundColor() const
535 return Color_color(Color::color(background_color_));
539 void Text::breakParagraph(Cursor & cur, bool keep_layout)
541 BOOST_ASSERT(this == cur.text());
543 Paragraph & cpar = cur.paragraph();
544 pit_type cpit = cur.pit();
546 TextClass const & tclass = cur.buffer().params().getTextClass();
547 LayoutPtr const & layout = cpar.layout();
549 // this is only allowed, if the current paragraph is not empty
550 // or caption and if it has not the keepempty flag active
551 if (cur.lastpos() == 0 && !cpar.allowEmpty() &&
552 layout->labeltype != LABEL_SENSITIVE)
555 // a layout change may affect also the following paragraph
556 recUndo(cur, cur.pit(), undoSpan(cur.pit()) - 1);
558 // Always break behind a space
559 // It is better to erase the space (Dekel)
560 if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
561 cpar.eraseChar(cur.pos(), cur.buffer().params().trackChanges);
563 // What should the layout for the new paragraph be?
564 int preserve_layout = 0;
568 preserve_layout = layout->isEnvironment();
570 // We need to remember this before we break the paragraph, because
571 // that invalidates the layout variable
572 bool sensitive = layout->labeltype == LABEL_SENSITIVE;
574 // we need to set this before we insert the paragraph.
575 bool const isempty = cpar.allowEmpty() && cpar.empty();
577 lyx::breakParagraph(cur.buffer().params(), paragraphs(), cpit,
578 cur.pos(), preserve_layout);
580 // After this, neither paragraph contains any rows!
583 pit_type next_par = cpit + 1;
585 // well this is the caption hack since one caption is really enough
588 // set to standard-layout
589 pars_[cpit].applyLayout(tclass.defaultLayout());
591 // set to standard-layout
592 pars_[next_par].applyLayout(tclass.defaultLayout());
595 while (!pars_[next_par].empty() && pars_[next_par].isNewline(0)) {
596 if (!pars_[next_par].eraseChar(0, cur.buffer().params().trackChanges))
597 break; // the character couldn't be deleted physically due to change tracking
600 updateLabels(cur.buffer());
602 // A singlePar update is not enough in this case.
603 cur.updateFlags(Update::Force);
605 // This check is necessary. Otherwise the new empty paragraph will
606 // be deleted automatically. And it is more friendly for the user!
607 if (cur.pos() != 0 || isempty)
608 setCursor(cur, cur.pit() + 1, 0);
610 setCursor(cur, cur.pit(), 0);
614 // insert a character, moves all the following breaks in the
615 // same Paragraph one to the right and make a rebreak
616 void Text::insertChar(Cursor & cur, char_type c)
618 BOOST_ASSERT(this == cur.text());
619 BOOST_ASSERT(c != Paragraph::META_INSET);
621 recordUndo(cur, Undo::INSERT);
623 Buffer const & buffer = cur.buffer();
624 Paragraph & par = cur.paragraph();
625 // try to remove this
626 pit_type const pit = cur.pit();
628 bool const freeSpacing = par.layout()->free_spacing ||
631 if (lyxrc.auto_number) {
632 static docstring const number_operators = from_ascii("+-/*");
633 static docstring const number_unary_operators = from_ascii("+-");
634 static docstring const number_seperators = from_ascii(".,:");
636 if (current_font.number() == Font::ON) {
637 if (!isDigit(c) && !contains(number_operators, c) &&
638 !(contains(number_seperators, c) &&
640 cur.pos() != cur.lastpos() &&
641 getFont(buffer, par, cur.pos()).number() == Font::ON &&
642 getFont(buffer, par, cur.pos() - 1).number() == Font::ON)
644 number(cur); // Set current_font.number to OFF
645 } else if (isDigit(c) &&
646 real_current_font.isVisibleRightToLeft()) {
647 number(cur); // Set current_font.number to ON
649 if (cur.pos() != 0) {
650 char_type const c = par.getChar(cur.pos() - 1);
651 if (contains(number_unary_operators, c) &&
653 || par.isSeparator(cur.pos() - 2)
654 || par.isNewline(cur.pos() - 2))
656 setCharFont(buffer, pit, cur.pos() - 1, current_font);
657 } else if (contains(number_seperators, c)
659 && getFont(buffer, par, cur.pos() - 2).number() == Font::ON) {
660 setCharFont(buffer, pit, cur.pos() - 1, current_font);
666 // In Bidi text, we want spaces to be treated in a special way: spaces
667 // which are between words in different languages should get the
668 // paragraph's language; otherwise, spaces should keep the language
669 // they were originally typed in. This is only in effect while typing;
670 // after the text is already typed in, the user can always go back and
671 // explicitly set the language of a space as desired. But 99.9% of the
672 // time, what we're doing here is what the user actually meant.
674 // The following cases are the ones in which the language of the space
675 // should be changed to match that of the containing paragraph. In the
676 // depictions, lowercase is LTR, uppercase is RTL, underscore (_)
677 // represents a space, pipe (|) represents the cursor position (so the
678 // character before it is the one just typed in). The different cases
679 // are depicted logically (not visually), from left to right:
684 // Theoretically, there are other situations that we should, perhaps, deal
685 // with (e.g.: a|_A, A|_a). In practice, though, there really isn't any
686 // point (to understand why, just try to create this situation...).
688 if ((cur.pos() >= 2) && (par.isLineSeparator(cur.pos() - 1))) {
689 // get font in front and behind the space in question. But do NOT
690 // use getFont(cur.pos()) because the character c is not inserted yet
691 Font const & pre_space_font = getFont(buffer, par, cur.pos() - 2);
692 Font const & post_space_font = real_current_font;
693 bool pre_space_rtl = pre_space_font.isVisibleRightToLeft();
694 bool post_space_rtl = post_space_font.isVisibleRightToLeft();
696 if (pre_space_rtl != post_space_rtl) {
697 // Set the space's language to match the language of the
698 // adjacent character whose direction is the paragraph's
699 // direction; don't touch other properties of the font
700 Language const * lang =
701 (pre_space_rtl == par.isRightToLeftPar(buffer.params())) ?
702 pre_space_font.language() : post_space_font.language();
704 Font space_font = getFont(buffer, par, cur.pos() - 1);
705 space_font.setLanguage(lang);
706 par.setFont(cur.pos() - 1, space_font);
710 // Next check, if there will be two blanks together or a blank at
711 // the beginning of a paragraph.
712 // I decided to handle blanks like normal characters, the main
713 // difference are the special checks when calculating the row.fill
714 // (blank does not count at the end of a row) and the check here
716 // When the free-spacing option is set for the current layout,
717 // disable the double-space checking
718 if (!freeSpacing && isLineSeparatorChar(c)) {
719 if (cur.pos() == 0) {
720 static bool sent_space_message = false;
721 if (!sent_space_message) {
722 cur.message(_("You cannot insert a space at the "
723 "beginning of a paragraph. Please read the Tutorial."));
724 sent_space_message = true;
728 BOOST_ASSERT(cur.pos() > 0);
729 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
730 && !par.isDeleted(cur.pos() - 1)) {
731 static bool sent_space_message = false;
732 if (!sent_space_message) {
733 cur.message(_("You cannot type two spaces this way. "
734 "Please read the Tutorial."));
735 sent_space_message = true;
741 par.insertChar(cur.pos(), c, current_font, cur.buffer().params().trackChanges);
742 checkBufferStructure(cur.buffer(), cur);
744 // cur.updateFlags(Update::Force);
745 setCursor(cur.top(), cur.pit(), cur.pos() + 1);
750 void Text::charInserted()
752 // Here we call finishUndo for every 20 characters inserted.
753 // This is from my experience how emacs does it. (Lgb)
754 static unsigned int counter;
764 // the cursor set functions have a special mechanism. When they
765 // realize, that you left an empty paragraph, they will delete it.
767 bool Text::cursorRightOneWord(Cursor & cur)
769 BOOST_ASSERT(this == cur.text());
773 if (old.pos() == old.lastpos() && old.pit() != old.lastpit()) {
777 // Advance through word.
778 while (old.pos() != old.lastpos() && old.paragraph().isLetter(old.pos()))
780 // Skip through trailing nonword stuff.
781 while (old.pos() != old.lastpos() && !old.paragraph().isLetter(old.pos()))
784 return setCursor(cur, old.pit(), old.pos());
788 bool Text::cursorLeftOneWord(Cursor & cur)
790 BOOST_ASSERT(this == cur.text());
794 if (old.pos() == 0 && old.pit() != 0) {
796 old.pos() = old.lastpos();
798 // Skip through initial nonword stuff.
799 while (old.pos() != 0 && !old.paragraph().isLetter(old.pos() - 1))
801 // Advance through word.
802 while (old.pos() != 0 && old.paragraph().isLetter(old.pos() - 1))
805 return setCursor(cur, old.pit(), old.pos());
809 void Text::selectWord(Cursor & cur, word_location loc)
811 BOOST_ASSERT(this == cur.text());
812 CursorSlice from = cur.top();
813 CursorSlice to = cur.top();
814 getWord(from, to, loc);
815 if (cur.top() != from)
816 setCursor(cur, from.pit(), from.pos());
820 setCursor(cur, to.pit(), to.pos());
825 // Select the word currently under the cursor when no
826 // selection is currently set
827 bool Text::selectWordWhenUnderCursor(Cursor & cur, word_location loc)
829 BOOST_ASSERT(this == cur.text());
832 selectWord(cur, loc);
833 return cur.selection();
837 void Text::acceptOrRejectChanges(Cursor & cur, ChangeOp op)
839 BOOST_ASSERT(this == cur.text());
841 if (!cur.selection())
844 recordUndoSelection(cur, Undo::ATOMIC);
846 pit_type begPit = cur.selectionBegin().pit();
847 pit_type endPit = cur.selectionEnd().pit();
849 pos_type begPos = cur.selectionBegin().pos();
850 pos_type endPos = cur.selectionEnd().pos();
852 // keep selection info, because endPos becomes invalid after the first loop
853 bool endsBeforeEndOfPar = (endPos < pars_[endPit].size());
855 // first, accept/reject changes within each individual paragraph (do not consider end-of-par)
857 for (pit_type pit = begPit; pit <= endPit; ++pit) {
858 pos_type parSize = pars_[pit].size();
860 // ignore empty paragraphs; otherwise, an assertion will fail for
861 // acceptChanges(bparams, 0, 0) or rejectChanges(bparams, 0, 0)
865 // do not consider first paragraph if the cursor starts at pos size()
866 if (pit == begPit && begPos == parSize)
869 // do not consider last paragraph if the cursor ends at pos 0
870 if (pit == endPit && endPos == 0)
871 break; // last iteration anyway
873 pos_type left = (pit == begPit ? begPos : 0);
874 pos_type right = (pit == endPit ? endPos : parSize);
877 pars_[pit].acceptChanges(cur.buffer().params(), left, right);
879 pars_[pit].rejectChanges(cur.buffer().params(), left, right);
883 // next, accept/reject imaginary end-of-par characters
885 for (pit_type pit = begPit; pit <= endPit; ++pit) {
886 pos_type pos = pars_[pit].size();
888 // skip if the selection ends before the end-of-par
889 if (pit == endPit && endsBeforeEndOfPar)
890 break; // last iteration anyway
892 // skip if this is not the last paragraph of the document
893 // note: the user should be able to accept/reject the par break of the last par!
894 if (pit == endPit && pit + 1 != int(pars_.size()))
895 break; // last iteration anway
898 if (pars_[pit].isInserted(pos)) {
899 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
900 } else if (pars_[pit].isDeleted(pos)) {
901 if (pit + 1 == int(pars_.size())) {
902 // we cannot remove a par break at the end of the last paragraph;
903 // instead, we mark it unchanged
904 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
906 mergeParagraph(cur.buffer().params(), pars_, pit);
912 if (pars_[pit].isDeleted(pos)) {
913 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
914 } else if (pars_[pit].isInserted(pos)) {
915 if (pit + 1 == int(pars_.size())) {
916 // we mark the par break at the end of the last paragraph unchanged
917 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
919 mergeParagraph(cur.buffer().params(), pars_, pit);
927 // finally, invoke the DEPM
929 deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer().params().trackChanges);
934 cur.clearSelection();
935 setCursorIntern(cur, begPit, begPos);
936 cur.updateFlags(Update::Force);
937 updateLabels(cur.buffer());
941 void Text::acceptChanges(BufferParams const & bparams)
943 lyx::acceptChanges(pars_, bparams);
944 deleteEmptyParagraphMechanism(0, pars_.size() - 1, bparams.trackChanges);
948 void Text::rejectChanges(BufferParams const & bparams)
950 pit_type pars_size = static_cast<pit_type>(pars_.size());
952 // first, reject changes within each individual paragraph
953 // (do not consider end-of-par)
954 for (pit_type pit = 0; pit < pars_size; ++pit) {
955 if (!pars_[pit].empty()) // prevent assertion failure
956 pars_[pit].rejectChanges(bparams, 0, pars_[pit].size());
959 // next, reject imaginary end-of-par characters
960 for (pit_type pit = 0; pit < pars_size; ++pit) {
961 pos_type pos = pars_[pit].size();
963 if (pars_[pit].isDeleted(pos)) {
964 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
965 } else if (pars_[pit].isInserted(pos)) {
966 if (pit == pars_size - 1) {
967 // we mark the par break at the end of the last
968 // paragraph unchanged
969 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
971 mergeParagraph(bparams, pars_, pit);
978 // finally, invoke the DEPM
979 deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.trackChanges);
983 // Delete from cursor up to the end of the current or next word.
984 void Text::deleteWordForward(Cursor & cur)
986 BOOST_ASSERT(this == cur.text());
987 if (cur.lastpos() == 0)
991 cur.selection() = true;
992 cursorRightOneWord(cur);
994 cutSelection(cur, true, false);
995 checkBufferStructure(cur.buffer(), cur);
1000 // Delete from cursor to start of current or prior word.
1001 void Text::deleteWordBackward(Cursor & cur)
1003 BOOST_ASSERT(this == cur.text());
1004 if (cur.lastpos() == 0)
1008 cur.selection() = true;
1009 cursorLeftOneWord(cur);
1011 cutSelection(cur, true, false);
1012 checkBufferStructure(cur.buffer(), cur);
1017 // Kill to end of line.
1018 void Text::deleteLineForward(Cursor & cur)
1020 BOOST_ASSERT(this == cur.text());
1021 if (cur.lastpos() == 0) {
1022 // Paragraph is empty, so we just go to the right
1026 cur.selection() = true; // to avoid deletion
1029 // What is this test for ??? (JMarc)
1030 if (!cur.selection())
1031 deleteWordForward(cur);
1033 cutSelection(cur, true, false);
1034 checkBufferStructure(cur.buffer(), cur);
1039 void Text::changeCase(Cursor & cur, Text::TextCase action)
1041 BOOST_ASSERT(this == cur.text());
1045 if (cur.selection()) {
1046 from = cur.selBegin();
1050 getWord(from, to, PARTIAL_WORD);
1051 cursorRightOneWord(cur);
1054 recordUndoSelection(cur, Undo::ATOMIC);
1056 pit_type begPit = from.pit();
1057 pit_type endPit = to.pit();
1059 pos_type begPos = from.pos();
1060 pos_type endPos = to.pos();
1062 bool const trackChanges = cur.buffer().params().trackChanges;
1064 pos_type right = 0; // needed after the for loop
1066 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1067 pos_type parSize = pars_[pit].size();
1069 pos_type pos = (pit == begPit ? begPos : 0);
1070 right = (pit == endPit ? endPos : parSize);
1072 // process sequences of modified characters; in change
1073 // tracking mode, this approach results in much better
1074 // usability than changing case on a char-by-char basis
1077 bool capitalize = true;
1079 for (; pos < right; ++pos) {
1080 char_type oldChar = pars_[pit].getChar(pos);
1081 char_type newChar = oldChar;
1083 // ignore insets and don't play with deleted text!
1084 if (oldChar != Paragraph::META_INSET && !pars_[pit].isDeleted(pos)) {
1086 case text_lowercase:
1087 newChar = lowercase(oldChar);
1089 case text_capitalization:
1091 newChar = uppercase(oldChar);
1095 case text_uppercase:
1096 newChar = uppercase(oldChar);
1101 if (!pars_[pit].isLetter(pos) || pars_[pit].isDeleted(pos)) {
1102 capitalize = true; // permit capitalization again
1105 if (oldChar != newChar) {
1109 if (oldChar == newChar || pos == right - 1) {
1110 if (oldChar != newChar) {
1111 pos++; // step behind the changing area
1113 int erasePos = pos - changes.size();
1114 for (size_t i = 0; i < changes.size(); i++) {
1115 pars_[pit].insertChar(pos, changes[i],
1116 pars_[pit].getFontSettings(cur.buffer().params(),
1119 if (!pars_[pit].eraseChar(erasePos, trackChanges)) {
1122 ++right; // expand selection
1130 // the selection may have changed due to logically-only deleted chars
1131 setCursor(cur, begPit, begPos);
1133 setCursor(cur, endPit, right);
1136 checkBufferStructure(cur.buffer(), cur);
1140 bool Text::handleBibitems(Cursor & cur)
1142 if (cur.paragraph().layout()->labeltype != LABEL_BIBLIO)
1144 // if a bibitem is deleted, merge with previous paragraph
1145 // if this is a bibliography item as well
1146 if (cur.pos() == 0) {
1147 BufferParams const & bufparams = cur.buffer().params();
1148 Paragraph const & par = cur.paragraph();
1149 Cursor prevcur = cur;
1150 if (cur.pit() > 0) {
1152 prevcur.pos() = prevcur.lastpos();
1154 Paragraph const & prevpar = prevcur.paragraph();
1155 if (cur.pit() > 0 && par.layout() == prevpar.layout()) {
1156 recordUndo(cur, Undo::ATOMIC, prevcur.pit());
1157 mergeParagraph(bufparams, cur.text()->paragraphs(),
1159 updateLabels(cur.buffer());
1160 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1161 cur.updateFlags(Update::Force);
1162 // if not, reset the paragraph to default
1164 cur.paragraph().layout(
1165 bufparams.getTextClass().defaultLayout());
1172 bool Text::erase(Cursor & cur)
1174 BOOST_ASSERT(this == cur.text());
1175 bool needsUpdate = false;
1176 Paragraph & par = cur.paragraph();
1178 if (cur.pos() != cur.lastpos()) {
1179 // this is the code for a normal delete, not pasting
1181 recordUndo(cur, Undo::DELETE);
1182 if(!par.eraseChar(cur.pos(), cur.buffer().params().trackChanges)) {
1183 // the character has been logically deleted only => skip it
1184 cur.top().forwardPos();
1186 checkBufferStructure(cur.buffer(), cur);
1189 if (cur.pit() == cur.lastpit())
1190 return dissolveInset(cur);
1192 if (!par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
1193 par.setChange(cur.pos(), Change(Change::DELETED));
1197 setCursorIntern(cur, cur.pit() + 1, 0);
1198 needsUpdate = backspacePos0(cur);
1202 needsUpdate |= handleBibitems(cur);
1205 // Make sure the cursor is correct. Is this really needed?
1206 // No, not really... at least not here!
1207 cur.text()->setCursor(cur.top(), cur.pit(), cur.pos());
1208 checkBufferStructure(cur.buffer(), cur);
1215 bool Text::backspacePos0(Cursor & cur)
1217 BOOST_ASSERT(this == cur.text());
1221 bool needsUpdate = false;
1223 BufferParams const & bufparams = cur.buffer().params();
1224 TextClass const & tclass = bufparams.getTextClass();
1225 ParagraphList & plist = cur.text()->paragraphs();
1226 Paragraph const & par = cur.paragraph();
1227 Cursor prevcur = cur;
1229 prevcur.pos() = prevcur.lastpos();
1230 Paragraph const & prevpar = prevcur.paragraph();
1232 // is it an empty paragraph?
1233 if (cur.lastpos() == 0
1234 || (cur.lastpos() == 1 && par.isSeparator(0))) {
1235 recordUndo(cur, Undo::ATOMIC, prevcur.pit(), cur.pit());
1236 plist.erase(boost::next(plist.begin(), cur.pit()));
1239 // is previous par empty?
1240 else if (prevcur.lastpos() == 0
1241 || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
1242 recordUndo(cur, Undo::ATOMIC, prevcur.pit(), cur.pit());
1243 plist.erase(boost::next(plist.begin(), prevcur.pit()));
1246 // Pasting is not allowed, if the paragraphs have different
1247 // layouts. I think it is a real bug of all other
1248 // word processors to allow it. It confuses the user.
1249 // Correction: Pasting is always allowed with standard-layout
1250 else if (par.layout() == prevpar.layout()
1251 || par.layout() == tclass.defaultLayout()) {
1252 recordUndo(cur, Undo::ATOMIC, prevcur.pit());
1253 mergeParagraph(bufparams, plist, prevcur.pit());
1258 updateLabels(cur.buffer());
1259 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1266 bool Text::backspace(Cursor & cur)
1268 BOOST_ASSERT(this == cur.text());
1269 bool needsUpdate = false;
1270 if (cur.pos() == 0) {
1272 return dissolveInset(cur);
1274 Paragraph & prev_par = pars_[cur.pit() - 1];
1276 if (!prev_par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
1277 prev_par.setChange(prev_par.size(), Change(Change::DELETED));
1278 setCursorIntern(cur, cur.pit() - 1, prev_par.size());
1281 // The cursor is at the beginning of a paragraph, so
1282 // the backspace will collapse two paragraphs into one.
1283 needsUpdate = backspacePos0(cur);
1286 // this is the code for a normal backspace, not pasting
1288 recordUndo(cur, Undo::DELETE);
1289 // We used to do cursorLeftIntern() here, but it is
1290 // not a good idea since it triggers the auto-delete
1291 // mechanism. So we do a cursorLeftIntern()-lite,
1292 // without the dreaded mechanism. (JMarc)
1293 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1294 false, cur.boundary());
1295 cur.paragraph().eraseChar(cur.pos(), cur.buffer().params().trackChanges);
1296 checkBufferStructure(cur.buffer(), cur);
1299 if (cur.pos() == cur.lastpos())
1300 setCurrentFont(cur);
1302 needsUpdate |= handleBibitems(cur);
1304 // A singlePar update is not enough in this case.
1305 // cur.updateFlags(Update::Force);
1306 setCursor(cur.top(), cur.pit(), cur.pos());
1312 bool Text::dissolveInset(Cursor & cur) {
1313 BOOST_ASSERT(this == cur.text());
1315 if (isMainText(cur.bv().buffer()) || cur.inset().nargs() != 1)
1318 recordUndoInset(cur);
1319 cur.selHandle(false);
1321 pos_type spos = cur.pos();
1322 pit_type spit = cur.pit();
1323 ParagraphList plist;
1324 if (cur.lastpit() != 0 || cur.lastpos() != 0)
1325 plist = paragraphs();
1327 // store cursor offset
1331 Buffer & b = cur.buffer();
1332 cur.paragraph().eraseChar(cur.pos(), b.params().trackChanges);
1333 if (!plist.empty()) {
1334 // ERT paragraphs have the Language latex_language.
1335 // This is invalid outside of ERT, so we need to
1336 // change it to the buffer language.
1337 ParagraphList::iterator it = plist.begin();
1338 ParagraphList::iterator it_end = plist.end();
1339 for (; it != it_end; it++) {
1340 it->changeLanguage(b.params(), latex_language,
1344 pasteParagraphList(cur, plist, b.params().getTextClass_ptr(),
1345 b.errorList("Paste"));
1347 cur.pit() = std::min(cur.lastpit(), spit);
1348 cur.pos() = std::min(cur.lastpos(), spos);
1350 cur.clearSelection();
1356 bool Text::isLastRow(pit_type pit, Row const & row) const
1358 return row.endpos() >= pars_[pit].size()
1359 && pit + 1 == pit_type(paragraphs().size());
1363 bool Text::isFirstRow(pit_type pit, Row const & row) const
1365 return row.pos() == 0 && pit == 0;
1369 void Text::getWord(CursorSlice & from, CursorSlice & to,
1370 word_location const loc)
1372 Paragraph const & from_par = pars_[from.pit()];
1374 case WHOLE_WORD_STRICT:
1375 if (from.pos() == 0 || from.pos() == from_par.size()
1376 || !from_par.isLetter(from.pos())
1377 || !from_par.isLetter(from.pos() - 1)) {
1381 // no break here, we go to the next
1384 // If we are already at the beginning of a word, do nothing
1385 if (!from.pos() || !from_par.isLetter(from.pos() - 1))
1387 // no break here, we go to the next
1390 // always move the cursor to the beginning of previous word
1391 while (from.pos() && from_par.isLetter(from.pos() - 1))
1395 lyxerr << "Text::getWord: NEXT_WORD not implemented yet"
1399 // no need to move the 'from' cursor
1403 Paragraph & to_par = pars_[to.pit()];
1404 while (to.pos() < to_par.size() && to_par.isLetter(to.pos()))
1409 void Text::write(Buffer const & buf, std::ostream & os) const
1411 ParagraphList::const_iterator pit = paragraphs().begin();
1412 ParagraphList::const_iterator end = paragraphs().end();
1414 for (; pit != end; ++pit)
1415 pit->write(buf, os, buf.params(), dth);
1417 // Close begin_deeper
1418 for(; dth > 0; --dth)
1419 os << "\n\\end_deeper";
1423 bool Text::read(Buffer const & buf, Lexer & lex, ErrorList & errorList)
1425 depth_type depth = 0;
1427 while (lex.isOK()) {
1429 string const token = lex.getString();
1434 if (token == "\\end_inset")
1437 if (token == "\\end_body")
1440 if (token == "\\begin_body")
1443 if (token == "\\end_document")
1446 if (token == "\\begin_layout") {
1447 lex.pushToken(token);
1450 par.params().depth(depth);
1451 par.setFont(0, Font(Font::ALL_INHERIT, buf.params().language));
1452 pars_.push_back(par);
1454 // FIXME: goddamn InsetTabular makes us pass a Buffer
1456 lyx::readParagraph(buf, pars_.back(), lex, errorList);
1458 } else if (token == "\\begin_deeper") {
1460 } else if (token == "\\end_deeper") {
1462 lex.printError("\\end_deeper: " "depth is already null");
1467 lyxerr << "Handling unknown body token: `"
1468 << token << '\'' << endl;
1474 int Text::cursorX(BufferView const & bv, CursorSlice const & sl,
1475 bool boundary) const
1477 TextMetrics const & tm = bv.textMetrics(sl.text());
1478 pit_type const pit = sl.pit();
1479 Paragraph const & par = pars_[pit];
1480 ParagraphMetrics const & pm = tm.parMetrics(pit);
1481 if (pm.rows().empty())
1484 pos_type ppos = sl.pos();
1485 // Correct position in front of big insets
1486 bool const boundary_correction = ppos != 0 && boundary;
1487 if (boundary_correction)
1490 Row const & row = pm.getRow(sl.pos(), boundary);
1492 pos_type cursor_vpos = 0;
1494 Buffer const & buffer = bv.buffer();
1497 bidi.computeTables(par, buffer, row);
1499 pos_type const row_pos = row.pos();
1500 pos_type const end = row.endpos();
1501 // Spaces at logical line breaks in bidi text must be skipped during
1502 // cursor positioning. However, they may appear visually in the middle
1503 // of a row; they must be skipped, wherever they are...
1504 // * logically "abc_[HEBREW_\nHEBREW]"
1505 // * visually "abc_[_WERBEH\nWERBEH]"
1506 pos_type skipped_sep_vpos = -1;
1509 cursor_vpos = row_pos;
1510 else if (ppos >= end)
1511 cursor_vpos = isRTL(buffer, par) ? row_pos : end;
1512 else if (ppos > row_pos && ppos >= end)
1513 // Place cursor after char at (logical) position pos - 1
1514 cursor_vpos = (bidi.level(ppos - 1) % 2 == 0)
1515 ? bidi.log2vis(ppos - 1) + 1 : bidi.log2vis(ppos - 1);
1517 // Place cursor before char at (logical) position ppos
1518 cursor_vpos = (bidi.level(ppos) % 2 == 0)
1519 ? bidi.log2vis(ppos) : bidi.log2vis(ppos) + 1;
1521 pos_type body_pos = par.beginOfBody();
1523 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1526 // Use font span to speed things up, see below
1530 // If the last logical character is a separator, skip it, unless
1531 // it's in the last row of a paragraph; see skipped_sep_vpos declaration
1532 if (end > 0 && end < par.size() && par.isSeparator(end - 1))
1533 skipped_sep_vpos = bidi.log2vis(end - 1);
1535 for (pos_type vpos = row_pos; vpos < cursor_vpos; ++vpos) {
1536 // Skip the separator which is at the logical end of the row
1537 if (vpos == skipped_sep_vpos)
1539 pos_type pos = bidi.vis2log(vpos);
1540 if (body_pos > 0 && pos == body_pos - 1) {
1541 FontMetrics const & labelfm = theFontMetrics(
1542 getLabelFont(buffer, par));
1543 x += row.label_hfill + labelfm.width(par.layout()->labelsep);
1544 if (par.isLineSeparator(body_pos - 1))
1545 x -= tm.singleWidth(pit, body_pos - 1);
1548 // Use font span to speed things up, see above
1549 if (pos < font_span.first || pos > font_span.last) {
1550 font_span = par.fontSpan(pos);
1551 font = getFont(buffer, par, pos);
1554 x += pm.singleWidth(pos, font);
1556 if (pm.hfillExpansion(row, pos))
1557 x += (pos >= body_pos) ? row.hfill : row.label_hfill;
1558 else if (par.isSeparator(pos) && pos >= body_pos)
1562 // see correction above
1563 if (boundary_correction) {
1564 if (isRTL(buffer, sl, boundary))
1565 x -= tm.singleWidth(pit, ppos);
1567 x += tm.singleWidth(pit, ppos);
1574 int Text::cursorY(BufferView const & bv, CursorSlice const & sl, bool boundary) const
1576 //lyxerr << "Text::cursorY: boundary: " << boundary << std::endl;
1577 ParagraphMetrics const & pm = bv.parMetrics(this, sl.pit());
1578 if (pm.rows().empty())
1582 h -= bv.parMetrics(this, 0).rows()[0].ascent();
1583 for (pit_type pit = 0; pit < sl.pit(); ++pit) {
1584 h += bv.parMetrics(this, pit).height();
1587 if (pos && boundary)
1589 size_t const rend = pm.pos2row(pos);
1590 for (size_t rit = 0; rit != rend; ++rit)
1591 h += pm.rows()[rit].height();
1592 h += pm.rows()[rend].ascent();
1597 // Returns the current font and depth as a message.
1598 docstring Text::currentState(Cursor & cur)
1600 BOOST_ASSERT(this == cur.text());
1601 Buffer & buf = cur.buffer();
1602 Paragraph const & par = cur.paragraph();
1603 odocstringstream os;
1605 if (buf.params().trackChanges)
1606 os << _("[Change Tracking] ");
1608 Change change = par.lookupChange(cur.pos());
1610 if (change.type != Change::UNCHANGED) {
1611 Author const & a = buf.params().authors().get(change.author);
1612 os << _("Change: ") << a.name();
1613 if (!a.email().empty())
1614 os << " (" << a.email() << ")";
1615 // FIXME ctime is english, we should translate that
1616 os << _(" at ") << ctime(&change.changetime);
1620 // I think we should only show changes from the default
1622 // No, from the document font (MV)
1623 Font font = real_current_font;
1624 font.reduce(buf.params().getFont());
1626 os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1628 // The paragraph depth
1629 int depth = cur.paragraph().getDepth();
1631 os << bformat(_(", Depth: %1$d"), depth);
1633 // The paragraph spacing, but only if different from
1635 Spacing const & spacing = par.params().spacing();
1636 if (!spacing.isDefault()) {
1637 os << _(", Spacing: ");
1638 switch (spacing.getSpace()) {
1639 case Spacing::Single:
1642 case Spacing::Onehalf:
1645 case Spacing::Double:
1648 case Spacing::Other:
1649 os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1651 case Spacing::Default:
1652 // should never happen, do nothing
1657 #ifdef DEVEL_VERSION
1658 os << _(", Inset: ") << &cur.inset();
1659 os << _(", Paragraph: ") << cur.pit();
1660 os << _(", Id: ") << par.id();
1661 os << _(", Position: ") << cur.pos();
1662 // FIXME: Why is the check for par.size() needed?
1663 // We are called with cur.pos() == par.size() quite often.
1664 if (!par.empty() && cur.pos() < par.size()) {
1665 // Force output of code point, not character
1666 size_t const c = par.getChar(cur.pos());
1667 os << _(", Char: 0x") << std::hex << c;
1669 os << _(", Boundary: ") << cur.boundary();
1670 // Row & row = cur.textRow();
1671 // os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
1677 docstring Text::getPossibleLabel(Cursor & cur) const
1679 pit_type pit = cur.pit();
1681 LayoutPtr layout = pars_[pit].layout();
1684 docstring par_text = pars_[pit].asString(cur.buffer(), false);
1685 for (int i = 0; i < lyxrc.label_init_length; ++i) {
1686 if (par_text.empty())
1689 par_text = split(par_text, head, ' ');
1690 // Is it legal to use spaces in labels ?
1696 // No need for a prefix if the user said so.
1697 if (lyxrc.label_init_length <= 0)
1700 // Will contain the label type.
1703 // For section, subsection, etc...
1704 if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
1705 LayoutPtr const & layout2 = pars_[pit - 1].layout();
1706 if (layout2->latextype != LATEX_PARAGRAPH) {
1711 if (layout->latextype != LATEX_PARAGRAPH)
1712 name = from_ascii(layout->latexname());
1714 // for captions, we just take the caption type
1715 Inset * caption_inset = cur.innerInsetOfType(Inset::CAPTION_CODE);
1717 name = from_ascii(static_cast<InsetCaption *>(caption_inset)->type());
1719 // If none of the above worked, we'll see if we're inside various
1720 // types of insets and take our abbreviation from them.
1722 Inset::Code const codes[] = {
1727 for (unsigned int i = 0; i < (sizeof codes / sizeof codes[0]); ++i) {
1728 Inset * float_inset = cur.innerInsetOfType(codes[i]);
1730 name = float_inset->name();
1736 // Create a correct prefix for prettyref
1737 if (name == "theorem")
1738 name = from_ascii("thm");
1739 else if (name == "Foot")
1740 name = from_ascii("fn");
1741 else if (name == "listing")
1742 name = from_ascii("lst");
1745 text = name.substr(0, 3) + ':' + text;
1751 void Text::setCursorFromCoordinates(Cursor & cur, int const x, int const y)
1753 BOOST_ASSERT(this == cur.text());
1754 pit_type pit = getPitNearY(cur.bv(), y);
1756 TextMetrics const & tm = cur.bv().textMetrics(this);
1757 ParagraphMetrics const & pm = tm.parMetrics(pit);
1759 int yy = cur.bv().coordCache().get(this, pit).y_ - pm.ascent();
1760 LYXERR(Debug::DEBUG)
1761 << BOOST_CURRENT_FUNCTION
1765 << " yy: " << yy << endl;
1768 BOOST_ASSERT(pm.rows().size());
1769 for (; r < int(pm.rows().size()) - 1; ++r) {
1770 Row const & row = pm.rows()[r];
1771 if (int(yy + row.height()) > y)
1776 Row const & row = pm.rows()[r];
1778 LYXERR(Debug::DEBUG)
1779 << BOOST_CURRENT_FUNCTION
1781 << " from pos: " << row.pos()
1786 pos_type const pos = row.pos()
1787 + tm.getColumnNearX(pit, row, xx, bound);
1789 LYXERR(Debug::DEBUG)
1790 << BOOST_CURRENT_FUNCTION
1791 << ": setting cursor pit: " << pit
1795 setCursor(cur, pit, pos, true, bound);
1796 // remember new position.
1801 void Text::charsTranspose(Cursor & cur)
1803 BOOST_ASSERT(this == cur.text());
1805 pos_type pos = cur.pos();
1807 // If cursor is at beginning or end of paragraph, do nothing.
1808 if (pos == cur.lastpos() || pos == 0)
1811 Paragraph & par = cur.paragraph();
1813 // Get the positions of the characters to be transposed.
1814 pos_type pos1 = pos - 1;
1815 pos_type pos2 = pos;
1817 // In change tracking mode, ignore deleted characters.
1818 while (pos2 < cur.lastpos() && par.isDeleted(pos2))
1820 if (pos2 == cur.lastpos())
1823 while (pos1 >= 0 && par.isDeleted(pos1))
1828 // Don't do anything if one of the "characters" is not regular text.
1829 if (par.isInset(pos1) || par.isInset(pos2))
1832 // Store the characters to be transposed (including font information).
1833 char_type char1 = par.getChar(pos1);
1835 par.getFontSettings(cur.buffer().params(), pos1);
1837 char_type char2 = par.getChar(pos2);
1839 par.getFontSettings(cur.buffer().params(), pos2);
1841 // And finally, we are ready to perform the transposition.
1842 // Track the changes if Change Tracking is enabled.
1843 bool const trackChanges = cur.buffer().params().trackChanges;
1847 par.eraseChar(pos2, trackChanges);
1848 par.eraseChar(pos1, trackChanges);
1849 par.insertChar(pos1, char2, font2, trackChanges);
1850 par.insertChar(pos2, char1, font1, trackChanges);
1852 checkBufferStructure(cur.buffer(), cur);
1854 // After the transposition, move cursor to after the transposition.
1855 setCursor(cur, cur.pit(), pos2);