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 Jean-Marc Lasgouttes
10 * \author André Pönitz
12 * \author Jürgen Vigna
14 * Full author contact details are available in file CREDITS.
23 #include "buffer_funcs.h"
24 #include "bufferparams.h"
25 #include "BufferView.h"
26 #include "bufferview_funcs.h"
28 #include "pariterator.h"
29 #include "coordcache.h"
30 #include "CutAndPaste.h"
32 #include "dispatchresult.h"
34 #include "errorlist.h"
35 #include "funcrequest.h"
37 #include "FontIterator.h"
41 #include "lyxlength.h"
45 #include "metricsinfo.h"
46 #include "paragraph.h"
47 #include "paragraph_funcs.h"
48 #include "ParagraphParameters.h"
49 #include "rowpainter.h"
52 #include "WordLangTuple.h"
54 #include "frontends/FontMetrics.h"
55 #include "frontends/Painter.h"
57 #include "insets/insettext.h"
58 #include "insets/insetbibitem.h"
59 #include "insets/insetcaption.h"
60 #include "insets/insethfill.h"
61 #include "insets/insetline.h"
62 #include "insets/insetnewline.h"
63 #include "insets/insetpagebreak.h"
64 #include "insets/insetoptarg.h"
65 #include "insets/insetspace.h"
66 #include "insets/insetspecialchar.h"
67 #include "insets/insettabular.h"
69 #include "support/lstrings.h"
70 #include "support/textutils.h"
71 #include "support/convert.h"
73 #include <boost/current_function.hpp>
87 using support::bformat;
88 using support::contains;
89 using support::lowercase;
91 using support::uppercase;
93 using cap::cutSelection;
94 using cap::pasteParagraphList;
96 using frontend::FontMetrics;
100 void readParToken(Buffer const & buf, Paragraph & par, LyXLex & lex,
101 string const & token, LyXFont & font, Change & change, ErrorList & errorList)
103 BufferParams const & bp = buf.params();
105 if (token[0] != '\\') {
107 string::const_iterator cit = token.begin();
108 for (; cit != token.end(); ++cit)
109 par.insertChar(par.size(), (*cit), font, change);
111 docstring dstr = lex.getDocString();
112 docstring::const_iterator cit = dstr.begin();
113 docstring::const_iterator cend = dstr.end();
114 for (; cit != cend; ++cit)
115 par.insertChar(par.size(), *cit, font, change);
117 } else if (token == "\\begin_layout") {
119 string layoutname = lex.getString();
121 font = LyXFont(LyXFont::ALL_INHERIT, bp.language);
122 change = Change(Change::UNCHANGED);
124 LyXTextClass const & tclass = bp.getLyXTextClass();
126 if (layoutname.empty()) {
127 layoutname = tclass.defaultLayoutName();
130 bool hasLayout = tclass.hasLayout(layoutname);
133 errorList.push_back(ErrorItem(_("Unknown layout"),
134 bformat(_("Layout '%1$s' does not exist in textclass '%2$s'\nTrying to use the default instead.\n"),
135 from_utf8(layoutname), from_utf8(tclass.name())), par.id(), 0, par.size()));
136 layoutname = tclass.defaultLayoutName();
139 par.layout(bp.getLyXTextClass()[layoutname]);
141 // Test whether the layout is obsolete.
142 LyXLayout_ptr const & layout = par.layout();
143 if (!layout->obsoleted_by().empty())
144 par.layout(bp.getLyXTextClass()[layout->obsoleted_by()]);
146 par.params().read(lex);
148 } else if (token == "\\end_layout") {
149 lyxerr << BOOST_CURRENT_FUNCTION
150 << ": Solitary \\end_layout in line "
151 << lex.getLineNo() << "\n"
152 << "Missing \\begin_layout?.\n";
153 } else if (token == "\\end_inset") {
154 lyxerr << BOOST_CURRENT_FUNCTION
155 << ": Solitary \\end_inset in line "
156 << lex.getLineNo() << "\n"
157 << "Missing \\begin_inset?.\n";
158 } else if (token == "\\begin_inset") {
159 InsetBase * inset = readInset(lex, buf);
161 par.insertInset(par.size(), inset, font, change);
164 docstring line = lex.getDocString();
165 errorList.push_back(ErrorItem(_("Unknown Inset"), line,
166 par.id(), 0, par.size()));
168 } else if (token == "\\family") {
170 font.setLyXFamily(lex.getString());
171 } else if (token == "\\series") {
173 font.setLyXSeries(lex.getString());
174 } else if (token == "\\shape") {
176 font.setLyXShape(lex.getString());
177 } else if (token == "\\size") {
179 font.setLyXSize(lex.getString());
180 } else if (token == "\\lang") {
182 string const tok = lex.getString();
183 Language const * lang = languages.getLanguage(tok);
185 font.setLanguage(lang);
187 font.setLanguage(bp.language);
188 lex.printError("Unknown language `$$Token'");
190 } else if (token == "\\numeric") {
192 font.setNumber(font.setLyXMisc(lex.getString()));
193 } else if (token == "\\emph") {
195 font.setEmph(font.setLyXMisc(lex.getString()));
196 } else if (token == "\\bar") {
198 string const tok = lex.getString();
201 font.setUnderbar(LyXFont::ON);
202 else if (tok == "no")
203 font.setUnderbar(LyXFont::OFF);
204 else if (tok == "default")
205 font.setUnderbar(LyXFont::INHERIT);
207 lex.printError("Unknown bar font flag "
209 } else if (token == "\\noun") {
211 font.setNoun(font.setLyXMisc(lex.getString()));
212 } else if (token == "\\color") {
214 font.setLyXColor(lex.getString());
215 } else if (token == "\\InsetSpace" || token == "\\SpecialChar") {
217 // Insets don't make sense in a free-spacing context! ---Kayvan
218 if (par.isFreeSpacing()) {
219 if (token == "\\InsetSpace")
220 par.insertChar(par.size(), ' ', font, change);
221 else if (lex.isOK()) {
223 string const next_token = lex.getString();
224 if (next_token == "\\-")
225 par.insertChar(par.size(), '-', font, change);
227 lex.printError("Token `$$Token' "
229 "paragraph layout!");
233 auto_ptr<InsetBase> inset;
234 if (token == "\\SpecialChar" )
235 inset.reset(new InsetSpecialChar);
237 inset.reset(new InsetSpace);
238 inset->read(buf, lex);
239 par.insertInset(par.size(), inset.release(),
242 } else if (token == "\\backslash") {
243 par.insertChar(par.size(), '\\', font, change);
244 } else if (token == "\\newline") {
245 auto_ptr<InsetBase> inset(new InsetNewline);
246 inset->read(buf, lex);
247 par.insertInset(par.size(), inset.release(), font, change);
248 } else if (token == "\\LyXTable") {
249 auto_ptr<InsetBase> inset(new InsetTabular(buf));
250 inset->read(buf, lex);
251 par.insertInset(par.size(), inset.release(), font, change);
252 } else if (token == "\\hfill") {
253 par.insertInset(par.size(), new InsetHFill, font, change);
254 } else if (token == "\\lyxline") {
255 par.insertInset(par.size(), new InsetLine, font, change);
256 } else if (token == "\\newpage") {
257 par.insertInset(par.size(), new InsetPagebreak, font, change);
258 } else if (token == "\\clearpage") {
259 par.insertInset(par.size(), new InsetClearPage, font, change);
260 } else if (token == "\\cleardoublepage") {
261 par.insertInset(par.size(), new InsetClearDoublePage, font, change);
262 } else if (token == "\\change_unchanged") {
263 change = Change(Change::UNCHANGED);
264 } else if (token == "\\change_inserted") {
266 std::istringstream is(lex.getString());
270 if (aid >= bp.author_map.size()) {
271 errorList.push_back(ErrorItem(_("Change tracking error"),
272 bformat(_("Unknown author index for insertion: %1$d\n"), aid),
273 par.id(), 0, par.size()));
274 change = Change(Change::UNCHANGED);
276 change = Change(Change::INSERTED, bp.author_map[aid], ct);
277 } else if (token == "\\change_deleted") {
279 std::istringstream is(lex.getString());
283 if (aid >= bp.author_map.size()) {
284 errorList.push_back(ErrorItem(_("Change tracking error"),
285 bformat(_("Unknown author index for deletion: %1$d\n"), aid),
286 par.id(), 0, par.size()));
287 change = Change(Change::UNCHANGED);
289 change = Change(Change::DELETED, bp.author_map[aid], ct);
292 errorList.push_back(ErrorItem(_("Unknown token"),
293 bformat(_("Unknown token: %1$s %2$s\n"), from_utf8(token),
295 par.id(), 0, par.size()));
300 void readParagraph(Buffer const & buf, Paragraph & par, LyXLex & lex,
301 ErrorList & errorList)
304 string token = lex.getString();
306 Change change(Change::UNCHANGED);
309 readParToken(buf, par, lex, token, font, change, errorList);
312 token = lex.getString();
317 if (token == "\\end_layout") {
318 //Ok, paragraph finished
322 lyxerr[Debug::PARSER] << "Handling paragraph token: `"
323 << token << '\'' << endl;
324 if (token == "\\begin_layout" || token == "\\end_document"
325 || token == "\\end_inset" || token == "\\begin_deeper"
326 || token == "\\end_deeper") {
327 lex.pushToken(token);
328 lyxerr << "Paragraph ended in line "
329 << lex.getLineNo() << "\n"
330 << "Missing \\end_layout.\n";
334 // Final change goes to paragraph break:
335 par.setChange(par.size(), change);
337 // Initialize begin_of_body_ on load; redoParagraph maintains
338 par.setBeginOfBody();
346 double LyXText::spacing(Buffer const & buffer,
347 Paragraph const & par) const
349 if (par.params().spacing().isDefault())
350 return buffer.params().spacing().getValue();
351 return par.params().spacing().getValue();
355 int LyXText::singleWidth(Buffer const & buffer, Paragraph const & par,
358 return singleWidth(par, pos, par.getChar(pos),
359 getFont(buffer, par, pos));
363 int LyXText::singleWidth(Paragraph const & par,
364 pos_type pos, char_type c, LyXFont const & font) const
366 // The most common case is handled first (Asger)
367 if (isPrintable(c)) {
368 Language const * language = font.language();
369 if (language->rightToLeft()) {
370 if (language->lang() == "arabic") {
371 if (Encodings::isComposeChar_arabic(c))
373 c = par.transformChar(c, pos);
374 } else if (language->lang() == "hebrew" &&
375 Encodings::isComposeChar_hebrew(c))
378 return theFontMetrics(font).width(c);
381 if (c == Paragraph::META_INSET)
382 return par.getInset(pos)->width();
384 return theFontMetrics(font).width(c);
388 int LyXText::leftMargin(Buffer const & buffer, int max_width, pit_type pit) const
390 BOOST_ASSERT(pit >= 0);
391 BOOST_ASSERT(pit < int(pars_.size()));
392 return leftMargin(buffer, max_width, pit, pars_[pit].size());
396 int LyXText::leftMargin(Buffer const & buffer, int max_width,
397 pit_type const pit, pos_type const pos) const
399 BOOST_ASSERT(pit >= 0);
400 BOOST_ASSERT(pit < int(pars_.size()));
401 Paragraph const & par = pars_[pit];
402 BOOST_ASSERT(pos >= 0);
403 BOOST_ASSERT(pos <= par.size());
404 //lyxerr << "LyXText::leftMargin: pit: " << pit << " pos: " << pos << endl;
405 LyXTextClass const & tclass = buffer.params().getLyXTextClass();
406 LyXLayout_ptr const & layout = par.layout();
408 string parindent = layout->parindent;
412 if (isMainText(buffer))
413 l_margin += changebarMargin();
416 docstring leftm = from_utf8(tclass.leftmargin());
417 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(leftm);
419 if (par.getDepth() != 0) {
420 // find the next level paragraph
421 pit_type newpar = outerHook(pit, pars_);
422 if (newpar != pit_type(pars_.size())) {
423 if (pars_[newpar].layout()->isEnvironment()) {
424 l_margin = leftMargin(buffer, max_width, newpar);
426 if (par.layout() == tclass.defaultLayout()) {
427 if (pars_[newpar].params().noindent())
430 parindent = pars_[newpar].layout()->parindent;
435 // This happens after sections in standard classes. The 1.3.x
436 // code compared depths too, but it does not seem necessary
438 if (par.layout() == tclass.defaultLayout()
439 && pit > 0 && pars_[pit - 1].layout()->nextnoindent)
442 LyXFont const labelfont = getLabelFont(buffer, par);
443 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
445 switch (layout->margintype) {
447 if (!layout->leftmargin.empty()) {
449 docstring leftm = from_utf8(layout->leftmargin);
450 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(leftm);
452 if (!par.getLabelstring().empty()) {
454 docstring labin = from_utf8(layout->labelindent);
455 l_margin += labelfont_metrics.signedWidth(labin);
456 docstring labstr = par.getLabelstring();
457 l_margin += labelfont_metrics.width(labstr);
458 docstring labsep = from_utf8(layout->labelsep);
459 l_margin += labelfont_metrics.width(labsep);
463 case MARGIN_MANUAL: {
465 docstring labin = from_utf8(layout->labelindent);
466 l_margin += labelfont_metrics.signedWidth(labin);
467 // The width of an empty par, even with manual label, should be 0
468 if (!par.empty() && pos >= par.beginOfBody()) {
469 if (!par.getLabelWidthString().empty()) {
470 docstring labstr = par.getLabelWidthString();
471 l_margin += labelfont_metrics.width(labstr);
472 docstring labsep = from_utf8(layout->labelsep);
473 l_margin += labelfont_metrics.width(labsep);
479 case MARGIN_STATIC: {
481 docstring leftm = from_utf8(layout->leftmargin);
482 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(leftm)
483 * 4 / (par.getDepth() + 4);
487 case MARGIN_FIRST_DYNAMIC:
488 if (layout->labeltype == LABEL_MANUAL) {
489 if (pos >= par.beginOfBody()) {
491 l_margin += labelfont_metrics.signedWidth(
492 from_utf8(layout->leftmargin));
495 l_margin += labelfont_metrics.signedWidth(
496 from_utf8(layout->labelindent));
499 // Special case to fix problems with
501 || (layout->labeltype == LABEL_STATIC
502 && layout->latextype == LATEX_ENVIRONMENT
503 && !isFirstInSequence(pit, pars_))) {
505 l_margin += labelfont_metrics.signedWidth(from_utf8(layout->leftmargin));
506 } else if (layout->labeltype != LABEL_TOP_ENVIRONMENT
507 && layout->labeltype != LABEL_BIBLIO
508 && layout->labeltype !=
509 LABEL_CENTERED_TOP_ENVIRONMENT) {
510 l_margin += labelfont_metrics.signedWidth(from_utf8(layout->labelindent));
511 l_margin += labelfont_metrics.width(from_utf8(layout->labelsep));
512 l_margin += labelfont_metrics.width(par.getLabelstring());
516 case MARGIN_RIGHT_ADDRESS_BOX: {
518 // ok, a terrible hack. The left margin depends on the widest
519 // row in this paragraph.
520 RowList::iterator rit = par.rows().begin();
521 RowList::iterator end = par.rows().end();
523 #warning This is wrong.
525 int minfill = max_width;
526 for ( ; rit != end; ++rit)
527 if (rit->fill() < minfill)
528 minfill = rit->fill();
529 l_margin += theFontMetrics(params.getFont()).signedWidth(layout->leftmargin);
532 // also wrong, but much shorter.
533 l_margin += max_width / 2;
538 if (!par.params().leftIndent().zero())
539 l_margin += par.params().leftIndent().inPixels(max_width);
543 if (par.params().align() == LYX_ALIGN_LAYOUT)
544 align = layout->align;
546 align = par.params().align();
548 // set the correct parindent
550 && (layout->labeltype == LABEL_NO_LABEL
551 || layout->labeltype == LABEL_TOP_ENVIRONMENT
552 || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
553 || (layout->labeltype == LABEL_STATIC
554 && layout->latextype == LATEX_ENVIRONMENT
555 && !isFirstInSequence(pit, pars_)))
556 && align == LYX_ALIGN_BLOCK
557 && !par.params().noindent()
558 // in some insets, paragraphs are never indented
559 && !(par.inInset() && par.inInset()->neverIndent(buffer))
560 // display style insets are always centered, omit indentation
563 && par.getInset(pos)->display())
564 && (par.layout() != tclass.defaultLayout()
565 || buffer.params().paragraph_separation ==
566 BufferParams::PARSEP_INDENT))
568 docstring din = from_utf8(parindent);
569 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(din);
576 LColor_color LyXText::backgroundColor() const
578 return LColor_color(LColor::color(background_color_));
582 void LyXText::breakParagraph(LCursor & cur, bool keep_layout)
584 BOOST_ASSERT(this == cur.text());
586 Paragraph & cpar = cur.paragraph();
587 pit_type cpit = cur.pit();
589 LyXTextClass const & tclass = cur.buffer().params().getLyXTextClass();
590 LyXLayout_ptr const & layout = cpar.layout();
592 // this is only allowed, if the current paragraph is not empty
593 // or caption and if it has not the keepempty flag active
594 if (cur.lastpos() == 0 && !cpar.allowEmpty() &&
595 layout->labeltype != LABEL_SENSITIVE)
598 // a layout change may affect also the following paragraph
599 recUndo(cur, cur.pit(), undoSpan(cur.pit()) - 1);
601 // Always break behind a space
602 // It is better to erase the space (Dekel)
603 if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
604 cpar.eraseChar(cur.pos(), cur.buffer().params().trackChanges);
606 // What should the layout for the new paragraph be?
607 int preserve_layout = 0;
611 preserve_layout = layout->isEnvironment();
613 // We need to remember this before we break the paragraph, because
614 // that invalidates the layout variable
615 bool sensitive = layout->labeltype == LABEL_SENSITIVE;
617 // we need to set this before we insert the paragraph.
618 bool const isempty = cpar.allowEmpty() && cpar.empty();
620 lyx::breakParagraph(cur.buffer().params(), paragraphs(), cpit,
621 cur.pos(), preserve_layout);
623 // After this, neither paragraph contains any rows!
626 pit_type next_par = cpit + 1;
628 // well this is the caption hack since one caption is really enough
631 // set to standard-layout
632 pars_[cpit].applyLayout(tclass.defaultLayout());
634 // set to standard-layout
635 pars_[next_par].applyLayout(tclass.defaultLayout());
638 while (!pars_[next_par].empty() && pars_[next_par].isNewline(0)) {
639 if (!pars_[next_par].eraseChar(0, cur.buffer().params().trackChanges))
640 break; // the character couldn't be deleted physically due to change tracking
643 ParIterator current_it(cur);
644 ParIterator last_it(cur);
648 updateLabels(cur.buffer(), current_it, last_it);
650 // A singlePar update is not enough in this case.
651 cur.updateFlags(Update::Force);
653 // This check is necessary. Otherwise the new empty paragraph will
654 // be deleted automatically. And it is more friendly for the user!
655 if (cur.pos() != 0 || isempty)
656 setCursor(cur.top(), cur.pit() + 1, 0);
658 setCursor(cur.top(), cur.pit(), 0);
662 // insert a character, moves all the following breaks in the
663 // same Paragraph one to the right and make a rebreak
664 void LyXText::insertChar(LCursor & cur, char_type c)
666 BOOST_ASSERT(this == cur.text());
667 BOOST_ASSERT(c != Paragraph::META_INSET);
669 recordUndo(cur, Undo::INSERT);
671 Buffer const & buffer = cur.buffer();
672 Paragraph & par = cur.paragraph();
673 // try to remove this
674 pit_type const pit = cur.pit();
676 bool const freeSpacing = par.layout()->free_spacing ||
679 if (lyxrc.auto_number) {
680 static docstring const number_operators = from_ascii("+-/*");
681 static docstring const number_unary_operators = from_ascii("+-");
682 static docstring const number_seperators = from_ascii(".,:");
684 if (current_font.number() == LyXFont::ON) {
685 if (!isDigit(c) && !contains(number_operators, c) &&
686 !(contains(number_seperators, c) &&
688 cur.pos() != cur.lastpos() &&
689 getFont(buffer, par, cur.pos()).number() == LyXFont::ON &&
690 getFont(buffer, par, cur.pos() - 1).number() == LyXFont::ON)
692 number(cur); // Set current_font.number to OFF
693 } else if (isDigit(c) &&
694 real_current_font.isVisibleRightToLeft()) {
695 number(cur); // Set current_font.number to ON
697 if (cur.pos() != 0) {
698 char_type const c = par.getChar(cur.pos() - 1);
699 if (contains(number_unary_operators, c) &&
701 || par.isSeparator(cur.pos() - 2)
702 || par.isNewline(cur.pos() - 2))
704 setCharFont(buffer, pit, cur.pos() - 1, current_font);
705 } else if (contains(number_seperators, c)
707 && getFont(buffer, par, cur.pos() - 2).number() == LyXFont::ON) {
708 setCharFont(buffer, pit, cur.pos() - 1, current_font);
714 // First check, if there will be two blanks together or a blank at
715 // the beginning of a paragraph.
716 // I decided to handle blanks like normal characters, the main
717 // difference are the special checks when calculating the row.fill
718 // (blank does not count at the end of a row) and the check here
720 // When the free-spacing option is set for the current layout,
721 // disable the double-space checking
722 if (!freeSpacing && isLineSeparatorChar(c)) {
723 if (cur.pos() == 0) {
724 static bool sent_space_message = false;
725 if (!sent_space_message) {
726 cur.message(_("You cannot insert a space at the "
727 "beginning of a paragraph. Please read the Tutorial."));
728 sent_space_message = true;
732 BOOST_ASSERT(cur.pos() > 0);
733 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
734 && !par.isDeleted(cur.pos() - 1)) {
735 static bool sent_space_message = false;
736 if (!sent_space_message) {
737 cur.message(_("You cannot type two spaces this way. "
738 "Please read the Tutorial."));
739 sent_space_message = true;
745 par.insertChar(cur.pos(), c, current_font, cur.buffer().params().trackChanges);
746 checkBufferStructure(cur.buffer(), cur);
748 // cur.updateFlags(Update::Force);
749 setCursor(cur.top(), cur.pit(), cur.pos() + 1);
754 void LyXText::charInserted()
756 // Here we call finishUndo for every 20 characters inserted.
757 // This is from my experience how emacs does it. (Lgb)
758 static unsigned int counter;
768 // the cursor set functions have a special mechanism. When they
769 // realize, that you left an empty paragraph, they will delete it.
771 bool LyXText::cursorRightOneWord(LCursor & cur)
773 BOOST_ASSERT(this == cur.text());
777 if (old.pos() == old.lastpos() && old.pit() != old.lastpit()) {
781 // Advance through word.
782 while (old.pos() != old.lastpos() && old.paragraph().isLetter(old.pos()))
784 // Skip through trailing nonword stuff.
785 while (old.pos() != old.lastpos() && !old.paragraph().isLetter(old.pos()))
788 return setCursor(cur, old.pit(), old.pos());
792 bool LyXText::cursorLeftOneWord(LCursor & cur)
794 BOOST_ASSERT(this == cur.text());
798 if (old.pos() == 0 && old.pit() != 0) {
800 old.pos() = old.lastpos();
802 // Skip through initial nonword stuff.
803 while (old.pos() != 0 && !old.paragraph().isLetter(old.pos() - 1))
805 // Advance through word.
806 while (old.pos() != 0 && old.paragraph().isLetter(old.pos() - 1))
809 return setCursor(cur, old.pit(), old.pos());
813 void LyXText::selectWord(LCursor & cur, word_location loc)
815 BOOST_ASSERT(this == cur.text());
816 CursorSlice from = cur.top();
817 CursorSlice to = cur.top();
818 getWord(from, to, loc);
819 if (cur.top() != from)
820 setCursor(cur, from.pit(), from.pos());
824 setCursor(cur, to.pit(), to.pos());
826 cap::saveSelection(cur);
830 // Select the word currently under the cursor when no
831 // selection is currently set
832 bool LyXText::selectWordWhenUnderCursor(LCursor & cur, word_location loc)
834 BOOST_ASSERT(this == cur.text());
837 selectWord(cur, loc);
838 return cur.selection();
842 void LyXText::acceptOrRejectChanges(LCursor & cur, ChangeOp op)
844 BOOST_ASSERT(this == cur.text());
846 if (!cur.selection())
849 recordUndoSelection(cur, Undo::ATOMIC);
851 pit_type begPit = cur.selectionBegin().pit();
852 pit_type endPit = cur.selectionEnd().pit();
854 pos_type begPos = cur.selectionBegin().pos();
855 pos_type endPos = cur.selectionEnd().pos();
857 // keep selection info, because endPos becomes invalid after the first loop
858 bool endsBeforeEndOfPar = (endPos < pars_[endPit].size());
860 // first, accept/reject changes within each individual paragraph (do not consider end-of-par)
862 for (pit_type pit = begPit; pit <= endPit; ++pit) {
863 pos_type parSize = pars_[pit].size();
865 // ignore empty paragraphs; otherwise, an assertion will fail for
866 // acceptChanges(bparams, 0, 0) or rejectChanges(bparams, 0, 0)
870 // do not consider first paragraph if the cursor starts at pos size()
871 if (pit == begPit && begPos == parSize)
874 // do not consider last paragraph if the cursor ends at pos 0
875 if (pit == endPit && endPos == 0)
876 break; // last iteration anyway
878 pos_type left = (pit == begPit ? begPos : 0);
879 pos_type right = (pit == endPit ? endPos : parSize);
882 pars_[pit].acceptChanges(cur.buffer().params(), left, right);
884 pars_[pit].rejectChanges(cur.buffer().params(), left, right);
888 // next, accept/reject imaginary end-of-par characters
890 for (pit_type pit = begPit; pit <= endPit; ++pit) {
891 pos_type pos = pars_[pit].size();
893 // skip if the selection ends before the end-of-par
894 if (pit == endPit && endsBeforeEndOfPar)
895 break; // last iteration anyway
897 // skip if this is not the last paragraph of the document
898 // note: the user should be able to accept/reject the par break of the last par!
899 if (pit == endPit && pit != pars_.size() - 1)
900 break; // last iteration anway
903 if (pars_[pit].isInserted(pos)) {
904 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
905 } else if (pars_[pit].isDeleted(pos)) {
906 if (pit == pars_.size() - 1) {
907 // we cannot remove a par break at the end of the last paragraph;
908 // instead, we mark it unchanged
909 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
911 mergeParagraph(cur.buffer().params(), pars_, pit);
917 if (pars_[pit].isDeleted(pos)) {
918 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
919 } else if (pars_[pit].isInserted(pos)) {
920 if (pit == pars_.size() - 1) {
921 // we mark the par break at the end of the last paragraph unchanged
922 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
924 mergeParagraph(cur.buffer().params(), pars_, pit);
932 // finally, invoke the DEPM
934 deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer().params().trackChanges);
939 cur.clearSelection();
940 setCursorIntern(cur, begPit, begPos);
941 cur.updateFlags(Update::Force);
942 updateLabels(cur.buffer());
946 void LyXText::acceptChanges(BufferParams const & bparams)
948 pit_type pars_size = static_cast<pit_type>(pars_.size());
950 // first, accept changes within each individual paragraph
951 // (do not consider end-of-par)
952 for (pit_type pit = 0; pit < pars_size; ++pit) {
953 if (!pars_[pit].empty()) // prevent assertion failure
954 pars_[pit].acceptChanges(bparams, 0, pars_[pit].size());
957 // next, accept imaginary end-of-par characters
958 for (pit_type pit = 0; pit < pars_size; ++pit) {
959 pos_type pos = pars_[pit].size();
961 if (pars_[pit].isInserted(pos)) {
962 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
963 } else if (pars_[pit].isDeleted(pos)) {
964 if (pit == pars_size - 1) {
965 // we cannot remove a par break at the end of the last
966 // paragraph; instead, we mark it unchanged
967 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
969 mergeParagraph(bparams, pars_, pit);
976 // finally, invoke the DEPM
977 deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.trackChanges);
981 void LyXText::rejectChanges(BufferParams const & bparams)
983 pit_type pars_size = static_cast<pit_type>(pars_.size());
985 // first, reject changes within each individual paragraph
986 // (do not consider end-of-par)
987 for (pit_type pit = 0; pit < pars_size; ++pit) {
988 if (!pars_[pit].empty()) // prevent assertion failure
989 pars_[pit].rejectChanges(bparams, 0, pars_[pit].size());
992 // next, reject imaginary end-of-par characters
993 for (pit_type pit = 0; pit < pars_size; ++pit) {
994 pos_type pos = pars_[pit].size();
996 if (pars_[pit].isDeleted(pos)) {
997 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
998 } else if (pars_[pit].isInserted(pos)) {
999 if (pit == pars_size - 1) {
1000 // we mark the par break at the end of the last
1001 // paragraph unchanged
1002 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1004 mergeParagraph(bparams, pars_, pit);
1011 // finally, invoke the DEPM
1012 deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.trackChanges);
1016 // Delete from cursor up to the end of the current or next word.
1017 void LyXText::deleteWordForward(LCursor & cur)
1019 BOOST_ASSERT(this == cur.text());
1020 if (cur.lastpos() == 0)
1024 cur.selection() = true;
1025 cursorRightOneWord(cur);
1027 cutSelection(cur, true, false);
1028 checkBufferStructure(cur.buffer(), cur);
1033 // Delete from cursor to start of current or prior word.
1034 void LyXText::deleteWordBackward(LCursor & cur)
1036 BOOST_ASSERT(this == cur.text());
1037 if (cur.lastpos() == 0)
1041 cur.selection() = true;
1042 cursorLeftOneWord(cur);
1044 cutSelection(cur, true, false);
1045 checkBufferStructure(cur.buffer(), cur);
1050 // Kill to end of line.
1051 void LyXText::deleteLineForward(LCursor & cur)
1053 BOOST_ASSERT(this == cur.text());
1054 if (cur.lastpos() == 0) {
1055 // Paragraph is empty, so we just go to the right
1059 cur.selection() = true; // to avoid deletion
1062 // What is this test for ??? (JMarc)
1063 if (!cur.selection())
1064 deleteWordForward(cur);
1066 cutSelection(cur, true, false);
1067 checkBufferStructure(cur.buffer(), cur);
1072 void LyXText::changeCase(LCursor & cur, LyXText::TextCase action)
1074 BOOST_ASSERT(this == cur.text());
1078 if (cur.selection()) {
1079 from = cur.selBegin();
1083 getWord(from, to, PARTIAL_WORD);
1084 cursorRightOneWord(cur);
1087 recordUndoSelection(cur, Undo::ATOMIC);
1089 pit_type begPit = from.pit();
1090 pit_type endPit = to.pit();
1092 pos_type begPos = from.pos();
1093 pos_type endPos = to.pos();
1095 bool const trackChanges = cur.buffer().params().trackChanges;
1097 pos_type right; // needed after the for loop
1099 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1100 pos_type parSize = pars_[pit].size();
1102 pos_type pos = (pit == begPit ? begPos : 0);
1103 right = (pit == endPit ? endPos : parSize);
1105 // process sequences of modified characters; in change
1106 // tracking mode, this approach results in much better
1107 // usability than changing case on a char-by-char basis
1110 bool capitalize = true;
1112 for (; pos < right; ++pos) {
1113 char_type oldChar = pars_[pit].getChar(pos);
1114 char_type newChar = oldChar;
1116 // ignore insets and don't play with deleted text!
1117 if (oldChar != Paragraph::META_INSET && !pars_[pit].isDeleted(pos)) {
1119 case text_lowercase:
1120 newChar = lowercase(oldChar);
1122 case text_capitalization:
1124 newChar = uppercase(oldChar);
1128 case text_uppercase:
1129 newChar = uppercase(oldChar);
1134 if (!pars_[pit].isLetter(pos) || pars_[pit].isDeleted(pos)) {
1135 capitalize = true; // permit capitalization again
1138 if (oldChar != newChar) {
1142 if (oldChar == newChar || pos == right - 1) {
1143 if (oldChar != newChar) {
1144 pos++; // step behind the changing area
1146 int erasePos = pos - changes.size();
1147 for (size_t i = 0; i < changes.size(); i++) {
1148 pars_[pit].insertChar(pos, changes[i],
1149 pars_[pit].getFontSettings(cur.buffer().params(),
1152 if (!pars_[pit].eraseChar(erasePos, trackChanges)) {
1155 ++right; // expand selection
1163 // the selection may have changed due to logically-only deleted chars
1164 setCursor(cur, begPit, begPos);
1166 setCursor(cur, endPit, right);
1169 checkBufferStructure(cur.buffer(), cur);
1173 bool LyXText::erase(LCursor & cur)
1175 BOOST_ASSERT(this == cur.text());
1176 bool needsUpdate = false;
1177 Paragraph & par = cur.paragraph();
1179 if (cur.pos() != cur.lastpos()) {
1180 // this is the code for a normal delete, not pasting
1182 recordUndo(cur, Undo::DELETE);
1183 if(!par.eraseChar(cur.pos(), cur.buffer().params().trackChanges)) {
1184 // the character has been logically deleted only => skip it
1185 cur.forwardPosNoDescend();
1187 checkBufferStructure(cur.buffer(), cur);
1190 if (cur.pit() == cur.lastpit())
1191 return dissolveInset(cur);
1193 if (!par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
1194 par.setChange(cur.pos(), Change(Change::DELETED));
1198 setCursorIntern(cur, cur.pit() + 1, 0);
1199 needsUpdate = backspacePos0(cur);
1204 // Make sure the cursor is correct. Is this really needed?
1205 // No, not really... at least not here!
1206 cur.text()->setCursor(cur.top(), cur.pit(), cur.pos());
1207 checkBufferStructure(cur.buffer(), cur);
1214 bool LyXText::backspacePos0(LCursor & cur)
1216 BOOST_ASSERT(this == cur.text());
1220 bool needsUpdate = false;
1222 BufferParams const & bufparams = cur.buffer().params();
1223 LyXTextClass const & tclass = bufparams.getLyXTextClass();
1224 ParagraphList & plist = cur.text()->paragraphs();
1225 Paragraph const & par = cur.paragraph();
1226 LCursor prevcur = cur;
1228 prevcur.pos() = prevcur.lastpos();
1229 Paragraph const & prevpar = prevcur.paragraph();
1231 // is it an empty paragraph?
1232 if (cur.lastpos() == 0
1233 || (cur.lastpos() == 1 && par.isSeparator(0))) {
1234 recordUndo(cur, Undo::ATOMIC, prevcur.pit(), cur.pit());
1235 plist.erase(boost::next(plist.begin(), cur.pit()));
1238 // is previous par empty?
1239 else if (prevcur.lastpos() == 0
1240 || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
1241 recordUndo(cur, Undo::ATOMIC, prevcur.pit(), cur.pit());
1242 plist.erase(boost::next(plist.begin(), prevcur.pit()));
1245 // Pasting is not allowed, if the paragraphs have different
1246 // layouts. I think it is a real bug of all other
1247 // word processors to allow it. It confuses the user.
1248 // Correction: Pasting is always allowed with standard-layout
1249 else if (par.layout() == prevpar.layout()
1250 || par.layout() == tclass.defaultLayout()) {
1251 recordUndo(cur, Undo::ATOMIC, prevcur.pit());
1252 mergeParagraph(bufparams, plist, prevcur.pit());
1257 updateLabels(cur.buffer());
1258 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1265 bool LyXText::backspace(LCursor & cur)
1267 BOOST_ASSERT(this == cur.text());
1268 bool needsUpdate = false;
1269 if (cur.pos() == 0) {
1271 return dissolveInset(cur);
1273 Paragraph & prev_par = pars_[cur.pit() - 1];
1275 if (!prev_par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
1276 prev_par.setChange(prev_par.size(), Change(Change::DELETED));
1277 setCursorIntern(cur, cur.pit() - 1, prev_par.size());
1280 // The cursor is at the beginning of a paragraph, so
1281 // the backspace will collapse two paragraphs into one.
1282 needsUpdate = backspacePos0(cur);
1285 // this is the code for a normal backspace, not pasting
1287 recordUndo(cur, Undo::DELETE);
1288 // We used to do cursorLeftIntern() here, but it is
1289 // not a good idea since it triggers the auto-delete
1290 // mechanism. So we do a cursorLeftIntern()-lite,
1291 // without the dreaded mechanism. (JMarc)
1292 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1293 false, cur.boundary());
1294 cur.paragraph().eraseChar(cur.pos(), cur.buffer().params().trackChanges);
1295 checkBufferStructure(cur.buffer(), cur);
1298 if (cur.pos() == cur.lastpos())
1299 setCurrentFont(cur);
1301 // A singlePar update is not enough in this case.
1302 // cur.updateFlags(Update::Force);
1303 setCursor(cur.top(), cur.pit(), cur.pos());
1309 bool LyXText::dissolveInset(LCursor & cur) {
1310 BOOST_ASSERT(this == cur.text());
1312 if (isMainText(*cur.bv().buffer()) || cur.inset().nargs() != 1)
1315 recordUndoInset(cur);
1316 cur.selHandle(false);
1318 pos_type spos = cur.pos();
1319 pit_type spit = cur.pit();
1320 ParagraphList plist;
1321 if (cur.lastpit() != 0 || cur.lastpos() != 0)
1322 plist = paragraphs();
1324 // store cursor offset
1328 Buffer & b = cur.buffer();
1329 cur.paragraph().eraseChar(cur.pos(), b.params().trackChanges);
1330 if (!plist.empty()) {
1331 // ERT paragraphs have the Language latex_language.
1332 // This is invalid outside of ERT, so we need to
1333 // change it to the buffer language.
1334 ParagraphList::iterator it = plist.begin();
1335 ParagraphList::iterator it_end = plist.end();
1336 for (; it != it_end; it++) {
1337 it->changeLanguage(b.params(), latex_language,
1341 pasteParagraphList(cur, plist, b.params().textclass,
1342 b.errorList("Paste"));
1344 cur.pit() = std::min(cur.lastpit(), spit);
1345 cur.pos() = std::min(cur.lastpos(), spos);
1347 cur.clearSelection();
1353 // only used for inset right now. should also be used for main text
1354 void LyXText::draw(PainterInfo & pi, int x, int y) const
1356 paintTextInset(*this, pi, x, y);
1360 // only used for inset right now. should also be used for main text
1361 void LyXText::drawSelection(PainterInfo & pi, int x, int) const
1363 LCursor & cur = pi.base.bv->cursor();
1364 if (!cur.selection())
1366 if (!ptr_cmp(cur.text(), this))
1369 if (lyxerr.debugging(Debug::DEBUG)) {
1370 lyxerr[Debug::DEBUG]
1371 << BOOST_CURRENT_FUNCTION
1372 << "draw selection at " << x
1376 DocIterator beg = cur.selectionBegin();
1377 DocIterator end = cur.selectionEnd();
1379 BufferView & bv = *pi.base.bv;
1380 Buffer const & buffer = *bv.buffer();
1382 // the selection doesn't touch the visible screen
1383 if (bv_funcs::status(&bv, beg) == bv_funcs::CUR_BELOW
1384 || bv_funcs::status(&bv, end) == bv_funcs::CUR_ABOVE)
1387 Paragraph const & par1 = pars_[beg.pit()];
1388 Paragraph const & par2 = pars_[end.pit()];
1389 TextMetrics const & tm = bv.textMetrics(this);
1390 ParagraphMetrics const & pm1 = tm.parMetrics(beg.pit());
1391 ParagraphMetrics const & pm2 = tm.parMetrics(end.pit());
1393 bool const above = (bv_funcs::status(&bv, beg)
1394 == bv_funcs::CUR_ABOVE);
1395 bool const below = (bv_funcs::status(&bv, end)
1396 == bv_funcs::CUR_BELOW);
1404 Row const & row1 = pm1.getRow(beg.pos(), beg.boundary());
1405 y1 = bv_funcs::getPos(bv, beg, beg.boundary()).y_ - row1.ascent();
1406 y2 = y1 + row1.height();
1407 int const startx = cursorX(bv, beg.top(), beg.boundary());
1408 if (!isRTL(buffer, par1)) {
1410 x2 = 0 + tm.width();
1420 Y1 = bv.workHeight();
1421 Y2 = bv.workHeight();
1425 Row const & row2 = pm2.getRow(end.pos(), end.boundary());
1426 Y1 = bv_funcs::getPos(bv, end, end.boundary()).y_ - row2.ascent();
1427 Y2 = Y1 + row2.height();
1428 int const endx = cursorX(bv, end.top(), end.boundary());
1429 if (!isRTL(buffer, par2)) {
1435 X2 = 0 + tm.width();
1439 if (!above && !below && &pm1.getRow(beg.pos(), beg.boundary())
1440 == &pm2.getRow(end.pos(), end.boundary()))
1442 // paint only one rectangle
1443 int const b( !isRTL(*bv.buffer(), par1) ? x + x1 : x + X1 );
1444 int const w( !isRTL(*bv.buffer(), par1) ? X2 - x1 : x2 - X1 );
1445 pi.pain.fillRectangle(b, y1, w, y2 - y1, LColor::selection);
1449 if (lyxerr.debugging(Debug::DEBUG)) {
1450 lyxerr[Debug::DEBUG] << " y1: " << y1 << " y2: " << y2
1451 << "X1:" << X1 << " x2: " << X2 << " wid: " << tm.width()
1455 // paint upper rectangle
1456 pi.pain.fillRectangle(x + x1, y1, x2 - x1, y2 - y1,
1458 // paint bottom rectangle
1459 pi.pain.fillRectangle(x + X1, Y1, X2 - X1, Y2 - Y1,
1461 // paint center rectangle
1462 pi.pain.fillRectangle(x, y2, tm.width(),
1463 Y1 - y2, LColor::selection);
1467 bool LyXText::isLastRow(pit_type pit, Row const & row) const
1469 return row.endpos() >= pars_[pit].size()
1470 && pit + 1 == pit_type(paragraphs().size());
1474 bool LyXText::isFirstRow(pit_type pit, Row const & row) const
1476 return row.pos() == 0 && pit == 0;
1480 void LyXText::getWord(CursorSlice & from, CursorSlice & to,
1481 word_location const loc)
1483 Paragraph const & from_par = pars_[from.pit()];
1485 case WHOLE_WORD_STRICT:
1486 if (from.pos() == 0 || from.pos() == from_par.size()
1487 || !from_par.isLetter(from.pos())
1488 || !from_par.isLetter(from.pos() - 1)) {
1492 // no break here, we go to the next
1495 // If we are already at the beginning of a word, do nothing
1496 if (!from.pos() || !from_par.isLetter(from.pos() - 1))
1498 // no break here, we go to the next
1501 // always move the cursor to the beginning of previous word
1502 while (from.pos() && from_par.isLetter(from.pos() - 1))
1506 lyxerr << "LyXText::getWord: NEXT_WORD not implemented yet"
1510 // no need to move the 'from' cursor
1514 Paragraph & to_par = pars_[to.pit()];
1515 while (to.pos() < to_par.size() && to_par.isLetter(to.pos()))
1520 void LyXText::write(Buffer const & buf, std::ostream & os) const
1522 ParagraphList::const_iterator pit = paragraphs().begin();
1523 ParagraphList::const_iterator end = paragraphs().end();
1525 for (; pit != end; ++pit)
1526 pit->write(buf, os, buf.params(), dth);
1530 bool LyXText::read(Buffer const & buf, LyXLex & lex, ErrorList & errorList)
1532 depth_type depth = 0;
1534 while (lex.isOK()) {
1536 string const token = lex.getString();
1541 if (token == "\\end_inset")
1544 if (token == "\\end_body")
1547 if (token == "\\begin_body")
1550 if (token == "\\end_document")
1553 if (token == "\\begin_layout") {
1554 lex.pushToken(token);
1557 par.params().depth(depth);
1558 par.setFont(0, LyXFont(LyXFont::ALL_INHERIT, buf.params().language));
1559 pars_.push_back(par);
1561 // FIXME: goddamn InsetTabular makes us pass a Buffer
1563 lyx::readParagraph(buf, pars_.back(), lex, errorList);
1565 } else if (token == "\\begin_deeper") {
1567 } else if (token == "\\end_deeper") {
1569 lex.printError("\\end_deeper: " "depth is already null");
1574 lyxerr << "Handling unknown body token: `"
1575 << token << '\'' << endl;
1581 int LyXText::cursorX(BufferView const & bv, CursorSlice const & sl,
1582 bool boundary) const
1584 TextMetrics const & tm = bv.textMetrics(sl.text());
1585 pit_type const pit = sl.pit();
1586 Paragraph const & par = pars_[pit];
1587 ParagraphMetrics const & pm = tm.parMetrics(pit);
1588 if (pm.rows().empty())
1591 pos_type ppos = sl.pos();
1592 // Correct position in front of big insets
1593 bool const boundary_correction = ppos != 0 && boundary;
1594 if (boundary_correction)
1597 Row const & row = pm.getRow(sl.pos(), boundary);
1599 pos_type cursor_vpos = 0;
1601 Buffer const & buffer = *bv.buffer();
1602 RowMetrics const m = tm.computeRowMetrics(pit, row);
1605 pos_type const row_pos = row.pos();
1606 pos_type const end = row.endpos();
1609 cursor_vpos = row_pos;
1610 else if (ppos >= end)
1611 cursor_vpos = isRTL(buffer, par) ? row_pos : end;
1612 else if (ppos > row_pos && ppos >= end)
1613 // Place cursor after char at (logical) position pos - 1
1614 cursor_vpos = (bidi.level(ppos - 1) % 2 == 0)
1615 ? bidi.log2vis(ppos - 1) + 1 : bidi.log2vis(ppos - 1);
1617 // Place cursor before char at (logical) position ppos
1618 cursor_vpos = (bidi.level(ppos) % 2 == 0)
1619 ? bidi.log2vis(ppos) : bidi.log2vis(ppos) + 1;
1621 pos_type body_pos = par.beginOfBody();
1623 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1626 // Use font span to speed things up, see below
1629 FontMetrics const & labelfm = theFontMetrics(
1630 getLabelFont(buffer, par));
1632 for (pos_type vpos = row_pos; vpos < cursor_vpos; ++vpos) {
1633 pos_type pos = bidi.vis2log(vpos);
1634 if (body_pos > 0 && pos == body_pos - 1) {
1636 docstring const lsep = from_utf8(par.layout()->labelsep);
1637 x += m.label_hfill + labelfm.width(lsep);
1638 if (par.isLineSeparator(body_pos - 1))
1639 x -= singleWidth(buffer, par, body_pos - 1);
1642 // Use font span to speed things up, see above
1643 if (pos < font_span.first || pos > font_span.last) {
1644 font_span = par.fontSpan(pos);
1645 font = getFont(buffer, par, pos);
1648 x += singleWidth(par, pos, par.getChar(pos), font);
1650 if (par.hfillExpansion(row, pos))
1651 x += (pos >= body_pos) ? m.hfill : m.label_hfill;
1652 else if (par.isSeparator(pos) && pos >= body_pos)
1656 // see correction above
1657 if (boundary_correction)
1658 if (getFont(buffer, par, ppos).isVisibleRightToLeft())
1659 x -= singleWidth(buffer, par, ppos);
1661 x += singleWidth(buffer, par, ppos);
1663 // Make sure inside an inset we always count from the left
1664 // edge (bidi!) -- MV
1665 if (sl.pos() < par.size()) {
1666 font = getFont(buffer, par, sl.pos());
1667 if (!boundary && font.isVisibleRightToLeft()
1668 && par.isInset(sl.pos()))
1669 x -= par.getInset(sl.pos())->width();
1675 int LyXText::cursorY(BufferView const & bv, CursorSlice const & sl, bool boundary) const
1677 //lyxerr << "LyXText::cursorY: boundary: " << boundary << std::endl;
1678 ParagraphMetrics const & pm = bv.parMetrics(this, sl.pit());
1679 if (pm.rows().empty())
1683 h -= bv.parMetrics(this, 0).rows()[0].ascent();
1684 for (pit_type pit = 0; pit < sl.pit(); ++pit) {
1685 h += bv.parMetrics(this, pit).height();
1688 if (pos && boundary)
1690 size_t const rend = pm.pos2row(pos);
1691 for (size_t rit = 0; rit != rend; ++rit)
1692 h += pm.rows()[rit].height();
1693 h += pm.rows()[rend].ascent();
1698 // Returns the current font and depth as a message.
1699 docstring LyXText::currentState(LCursor & cur)
1701 BOOST_ASSERT(this == cur.text());
1702 Buffer & buf = cur.buffer();
1703 Paragraph const & par = cur.paragraph();
1704 odocstringstream os;
1706 if (buf.params().trackChanges)
1707 os << _("[Change Tracking] ");
1709 Change change = par.lookupChange(cur.pos());
1711 if (change.type != Change::UNCHANGED) {
1712 Author const & a = buf.params().authors().get(change.author);
1713 os << _("Change: ") << a.name();
1714 if (!a.email().empty())
1715 os << " (" << a.email() << ")";
1716 // FIXME ctime is english, we should translate that
1717 os << _(" at ") << ctime(&change.changetime);
1721 // I think we should only show changes from the default
1723 // No, from the document font (MV)
1724 LyXFont font = real_current_font;
1725 font.reduce(buf.params().getFont());
1727 os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1729 // The paragraph depth
1730 int depth = cur.paragraph().getDepth();
1732 os << bformat(_(", Depth: %1$d"), depth);
1734 // The paragraph spacing, but only if different from
1736 Spacing const & spacing = par.params().spacing();
1737 if (!spacing.isDefault()) {
1738 os << _(", Spacing: ");
1739 switch (spacing.getSpace()) {
1740 case Spacing::Single:
1743 case Spacing::Onehalf:
1746 case Spacing::Double:
1749 case Spacing::Other:
1750 os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1752 case Spacing::Default:
1753 // should never happen, do nothing
1758 #ifdef DEVEL_VERSION
1759 os << _(", Inset: ") << &cur.inset();
1760 os << _(", Paragraph: ") << cur.pit();
1761 os << _(", Id: ") << par.id();
1762 os << _(", Position: ") << cur.pos();
1763 // FIXME: Why is the check for par.size() needed?
1764 // We are called with cur.pos() == par.size() quite often.
1765 if (!par.empty() && cur.pos() < par.size()) {
1766 // Force output of code point, not character
1767 size_t const c = par.getChar(cur.pos());
1768 os << _(", Char: 0x") << std::hex << c;
1770 os << _(", Boundary: ") << cur.boundary();
1771 // Row & row = cur.textRow();
1772 // os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
1778 docstring LyXText::getPossibleLabel(LCursor & cur) const
1780 pit_type pit = cur.pit();
1782 LyXLayout_ptr layout = pars_[pit].layout();
1785 docstring par_text = pars_[pit].asString(cur.buffer(), false);
1786 for (int i = 0; i < lyxrc.label_init_length; ++i) {
1787 if (par_text.empty())
1790 par_text = split(par_text, head, ' ');
1791 // Is it legal to use spaces in labels ?
1797 // No need for a prefix if the user said so.
1798 if (lyxrc.label_init_length <= 0)
1801 // Will contain the label type.
1804 // For section, subsection, etc...
1805 if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
1806 LyXLayout_ptr const & layout2 = pars_[pit - 1].layout();
1807 if (layout2->latextype != LATEX_PARAGRAPH) {
1812 if (layout->latextype != LATEX_PARAGRAPH)
1813 name = from_ascii(layout->latexname());
1815 // for captions, we just take the caption type
1816 InsetBase * caption_inset = cur.innerInsetOfType(InsetBase::CAPTION_CODE);
1818 name = from_ascii(static_cast<InsetCaption *>(caption_inset)->type());
1820 // Inside floats or wraps, if none of the above worked
1821 // we want by default the abbreviation of the float type.
1823 InsetBase * float_inset = cur.innerInsetOfType(InsetBase::FLOAT_CODE);
1825 float_inset = cur.innerInsetOfType(InsetBase::WRAP_CODE);
1827 name = float_inset->getInsetName();
1830 // Create a correct prefix for prettyref
1831 if (name == "theorem")
1832 name = from_ascii("thm");
1835 text = name.substr(0, 3) + ':' + text;
1841 void LyXText::setCursorFromCoordinates(LCursor & cur, int const x, int const y)
1843 BOOST_ASSERT(this == cur.text());
1844 pit_type pit = getPitNearY(cur.bv(), y);
1846 TextMetrics const & tm = cur.bv().textMetrics(this);
1847 ParagraphMetrics const & pm = tm.parMetrics(pit);
1849 int yy = cur.bv().coordCache().get(this, pit).y_ - pm.ascent();
1850 lyxerr[Debug::DEBUG]
1851 << BOOST_CURRENT_FUNCTION
1855 << " yy: " << yy << endl;
1858 BOOST_ASSERT(pm.rows().size());
1859 for (; r < int(pm.rows().size()) - 1; ++r) {
1860 Row const & row = pm.rows()[r];
1861 if (int(yy + row.height()) > y)
1866 Row const & row = pm.rows()[r];
1868 lyxerr[Debug::DEBUG]
1869 << BOOST_CURRENT_FUNCTION
1871 << " from pos: " << row.pos()
1876 pos_type const pos = row.pos()
1877 + tm.getColumnNearX(pit, row, xx, bound);
1879 lyxerr[Debug::DEBUG]
1880 << BOOST_CURRENT_FUNCTION
1881 << ": setting cursor pit: " << pit
1885 setCursor(cur, pit, pos, true, bound);
1886 // remember new position.
1891 void LyXText::charsTranspose(LCursor & cur)
1893 BOOST_ASSERT(this == cur.text());
1895 pos_type pos = cur.pos();
1897 // If cursor is at beginning or end of paragraph, do nothing.
1898 if (pos == cur.lastpos() || pos == 0)
1901 Paragraph & par = cur.paragraph();
1903 // Get the positions of the characters to be transposed.
1904 pos_type pos1 = pos - 1;
1905 pos_type pos2 = pos;
1907 // In change tracking mode, ignore deleted characters.
1908 while (pos2 < cur.lastpos() && par.isDeleted(pos2))
1910 if (pos2 == cur.lastpos())
1913 while (pos1 >= 0 && par.isDeleted(pos1))
1918 // Don't do anything if one of the "characters" is not regular text.
1919 if (par.isInset(pos1) || par.isInset(pos2))
1922 // Store the characters to be transposed (including font information).
1923 char_type char1 = par.getChar(pos1);
1924 LyXFont const font1 =
1925 par.getFontSettings(cur.buffer().params(), pos1);
1927 char_type char2 = par.getChar(pos2);
1928 LyXFont const font2 =
1929 par.getFontSettings(cur.buffer().params(), pos2);
1931 // And finally, we are ready to perform the transposition.
1932 // Track the changes if Change Tracking is enabled.
1933 bool const trackChanges = cur.buffer().params().trackChanges;
1937 par.eraseChar(pos2, trackChanges);
1938 par.eraseChar(pos1, trackChanges);
1939 par.insertChar(pos1, char2, font2, trackChanges);
1940 par.insertChar(pos2, char1, font1, trackChanges);
1942 checkBufferStructure(cur.buffer(), cur);
1944 // After the transposition, move cursor to after the transposition.
1945 setCursor(cur, cur.pit(), pos2);