2 * \file CutAndPaste.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Lars Gullik Bjønnes
8 * \author Alfredo Braunstein
11 * Full author contact details are available in file CREDITS.
16 #include "CutAndPaste.h"
18 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "BufferView.h"
27 #include "ErrorList.h"
29 #include "FuncRequest.h"
30 #include "InsetIterator.h"
31 #include "InsetList.h"
36 #include "Paragraph.h"
37 #include "ParagraphParameters.h"
38 #include "ParIterator.h"
39 #include "TextClass.h"
41 #include "insets/InsetBibitem.h"
42 #include "insets/InsetBranch.h"
43 #include "insets/InsetCommand.h"
44 #include "insets/InsetFlex.h"
45 #include "insets/InsetGraphics.h"
46 #include "insets/InsetGraphicsParams.h"
47 #include "insets/InsetInclude.h"
48 #include "insets/InsetLabel.h"
49 #include "insets/InsetTabular.h"
51 #include "mathed/MathData.h"
52 #include "mathed/InsetMath.h"
53 #include "mathed/InsetMathHull.h"
54 #include "mathed/InsetMathRef.h"
55 #include "mathed/MathSupport.h"
57 #include "support/debug.h"
58 #include "support/docstream.h"
59 #include "support/gettext.h"
60 #include "support/lassert.h"
61 #include "support/limited_stack.h"
62 #include "support/lstrings.h"
63 #include "support/TempFile.h"
65 #include "frontends/alert.h"
66 #include "frontends/Clipboard.h"
67 #include "frontends/Selection.h"
69 #include <boost/tuple/tuple.hpp>
70 #include <boost/next_prior.hpp>
75 using namespace lyx::support;
76 using lyx::frontend::Clipboard;
82 typedef pair<pit_type, int> PitPosPair;
84 typedef limited_stack<pair<ParagraphList, DocumentClassConstPtr> > CutStack;
87 // persistent selection, cleared until the next selection
88 CutStack selectionBuffer(1);
90 // store whether the tabular stack is newer than the normal copy stack
91 // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
92 // when we (hopefully) have a one-for-all paste mechanism.
93 bool dirty_tabular_stack_ = false;
96 bool checkPastePossible(int index)
98 return size_t(index) < theCuts.size() && !theCuts[index].first.empty();
102 struct PasteReturnValue {
103 PasteReturnValue(pit_type r_par, pos_type r_pos, bool r_nu) :
104 par(r_par), pos(r_pos), needupdate(r_nu)
113 pasteSelectionHelper(DocIterator const & cur, ParagraphList const & parlist,
114 DocumentClassConstPtr oldDocClass, Buffer * tmpbuffer,
115 ErrorList & errorlist)
117 Buffer const & buffer = *cur.buffer();
118 pit_type pit = cur.pit();
119 pos_type pos = cur.pos();
120 bool need_update = false;
121 InsetText * target_inset = cur.inset().asInsetText();
123 InsetTabular * it = cur.inset().asInsetTabular();
124 target_inset = it? it->cell(cur.idx())->asInsetText() : 0;
126 LASSERT(target_inset, return PasteReturnValue(pit, pos, need_update));
127 ParagraphList & pars = target_inset->paragraphs();
130 return PasteReturnValue(pit, pos, need_update);
132 BOOST_ASSERT (pos <= pars[pit].size());
134 // Make a copy of the CaP paragraphs.
135 ParagraphList insertion = parlist;
136 DocumentClassConstPtr newDocClass = buffer.params().documentClassPtr();
138 // Now remove all out of the pars which is NOT allowed in the
139 // new environment and set also another font if that is required.
141 // Convert newline to paragraph break in ParbreakIsNewline
142 if (target_inset->getLayout().parbreakIsNewline()
143 || pars[pit].layout().parbreak_is_newline) {
144 for (size_t i = 0; i != insertion.size(); ++i) {
145 for (pos_type j = 0; j != insertion[i].size(); ++j) {
146 if (insertion[i].isNewline(j)) {
147 // do not track deletion of newline
148 insertion[i].eraseChar(j, false);
149 insertion[i].setInsetOwner(target_inset);
150 breakParagraphConservative(
159 // set the paragraphs to plain layout if necessary
160 if (cur.inset().usePlainLayout()) {
161 bool forcePlainLayout = cur.inset().forcePlainLayout();
162 Layout const & plainLayout = newDocClass->plainLayout();
163 Layout const & defaultLayout = newDocClass->defaultLayout();
164 ParagraphList::iterator const end = insertion.end();
165 ParagraphList::iterator par = insertion.begin();
166 for (; par != end; ++par) {
167 Layout const & parLayout = par->layout();
168 if (forcePlainLayout || parLayout == defaultLayout)
169 par->setLayout(plainLayout);
171 } else { // check if we need to reset from plain layout
172 Layout const & defaultLayout = newDocClass->defaultLayout();
173 Layout const & plainLayout = newDocClass->plainLayout();
174 ParagraphList::iterator const end = insertion.end();
175 ParagraphList::iterator par = insertion.begin();
176 for (; par != end; ++par) {
177 Layout const & parLayout = par->layout();
178 if (parLayout == plainLayout)
179 par->setLayout(defaultLayout);
183 InsetText in(cur.buffer());
184 // Make sure there is no class difference.
185 in.paragraphs().clear();
186 // This works without copying any paragraph data because we have
187 // a specialized swap method for ParagraphList. This is important
188 // since we store pointers to insets at some places and we don't
189 // want to invalidate them.
190 insertion.swap(in.paragraphs());
191 cap::switchBetweenClasses(oldDocClass, newDocClass, in, errorlist);
192 insertion.swap(in.paragraphs());
194 ParagraphList::iterator tmpbuf = insertion.begin();
195 int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
197 depth_type max_depth = pars[pit].getMaxDepthAfter();
199 for (; tmpbuf != insertion.end(); ++tmpbuf) {
200 // If we have a negative jump so that the depth would
201 // go below 0 depth then we have to redo the delta to
202 // this new max depth level so that subsequent
203 // paragraphs are aligned correctly to this paragraph
205 if (int(tmpbuf->params().depth()) + depth_delta < 0)
208 // Set the right depth so that we are not too deep or shallow.
209 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
210 if (tmpbuf->params().depth() > max_depth)
211 tmpbuf->params().depth(max_depth);
213 // Set max_depth for the next paragraph
214 max_depth = tmpbuf->getMaxDepthAfter();
216 // Set the inset owner of this paragraph.
217 tmpbuf->setInsetOwner(target_inset);
218 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
219 // do not track deletion of invalid insets
220 if (Inset * inset = tmpbuf->getInset(i))
221 if (!target_inset->insetAllowed(inset->lyxCode()))
222 tmpbuf->eraseChar(i--, false);
225 tmpbuf->setChange(Change(buffer.params().track_changes ?
226 Change::INSERTED : Change::UNCHANGED));
229 bool const empty = pars[pit].empty();
231 // Make the buf exactly the same layout as the cursor
233 insertion.begin()->makeSameLayout(pars[pit]);
236 // Prepare the paragraphs and insets for insertion.
237 insertion.swap(in.paragraphs());
239 InsetIterator const i_end = inset_iterator_end(in);
240 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
241 // Even though this will also be done later, it has to be done here
242 // since some inset might going to try to access
243 // the buffer() member.
244 it->setBuffer(const_cast<Buffer &>(buffer));
245 switch (it->lyxCode()) {
247 case MATH_HULL_CODE: {
248 // check for equation labels and resolve duplicates
249 InsetMathHull * ins = it->asInsetMath()->asHullInset();
250 std::vector<InsetLabel *> labels = ins->getLabels();
251 for (size_t i = 0; i != labels.size(); ++i) {
254 InsetLabel * lab = labels[i];
255 docstring const oldname = lab->getParam("name");
256 lab->updateLabel(oldname);
257 // We need to update the buffer reference cache.
259 docstring const newname = lab->getParam("name");
260 if (oldname == newname)
262 // adapt the references
263 for (InsetIterator itt = inset_iterator_begin(in);
264 itt != i_end; ++itt) {
265 if (itt->lyxCode() == REF_CODE) {
266 InsetCommand * ref = itt->asInsetCommand();
267 if (ref->getParam("reference") == oldname)
268 ref->setParam("reference", newname);
269 } else if (itt->lyxCode() == MATH_REF_CODE) {
270 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
271 // this is necessary to prevent an uninitialized
272 // buffer when the RefInset is in a MathBox.
273 // FIXME audit setBuffer calls
274 mi->setBuffer(const_cast<Buffer &>(buffer));
275 if (mi->getTarget() == oldname)
276 mi->changeTarget(newname);
284 // check for duplicates
285 InsetLabel & lab = static_cast<InsetLabel &>(*it);
286 docstring const oldname = lab.getParam("name");
287 lab.updateLabel(oldname);
288 // We need to update the buffer reference cache.
290 docstring const newname = lab.getParam("name");
291 if (oldname == newname)
293 // adapt the references
294 for (InsetIterator itt = inset_iterator_begin(in); itt != i_end; ++itt) {
295 if (itt->lyxCode() == REF_CODE) {
296 InsetCommand & ref = static_cast<InsetCommand &>(*itt);
297 if (ref.getParam("reference") == oldname)
298 ref.setParam("reference", newname);
299 } else if (itt->lyxCode() == MATH_REF_CODE) {
300 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
301 // this is necessary to prevent an uninitialized
302 // buffer when the RefInset is in a MathBox.
303 // FIXME audit setBuffer calls
304 mi->setBuffer(const_cast<Buffer &>(buffer));
305 if (mi->getTarget() == oldname)
306 mi->changeTarget(newname);
313 InsetInclude & inc = static_cast<InsetInclude &>(*it);
315 // We need to update the list of included files.
321 // check for duplicates
322 InsetBibitem & bib = static_cast<InsetBibitem &>(*it);
323 docstring const oldkey = bib.getParam("key");
324 bib.updateCommand(oldkey, false);
325 // We need to update the buffer reference cache.
327 docstring const newkey = bib.getParam("key");
328 if (oldkey == newkey)
330 // adapt the references
331 for (InsetIterator itt = inset_iterator_begin(in);
332 itt != i_end; ++itt) {
333 if (itt->lyxCode() == CITE_CODE) {
334 InsetCommand * ref = itt->asInsetCommand();
335 if (ref->getParam("key") == oldkey)
336 ref->setParam("key", newkey);
343 // check if branch is known to target buffer
345 InsetBranch & br = static_cast<InsetBranch &>(*it);
346 docstring const name = br.branch();
349 bool const is_child = (&buffer != buffer.masterBuffer());
350 BranchList branchlist = buffer.params().branchlist();
351 if ((!is_child && branchlist.find(name))
352 || (is_child && (branchlist.find(name)
353 || buffer.masterBuffer()->params().branchlist().find(name))))
356 // This is for a temporary buffer, so simply create the branch.
357 // Must not use lyx::dispatch(), since tmpbuffer has no view.
359 tmpbuffer->dispatch(FuncRequest(LFUN_BRANCH_ADD, name), dr);
361 docstring text = bformat(
362 _("The pasted branch \"%1$s\" is undefined.\n"
363 "Do you want to add it to the document's branch list?"),
365 if (frontend::Alert::prompt(_("Unknown branch"),
366 text, 0, 1, _("&Add"), _("&Don't Add")) != 0)
368 lyx::dispatch(FuncRequest(LFUN_BRANCH_ADD, name));
370 // We need to update the list of branches.
379 insertion.swap(in.paragraphs());
381 // Split the paragraph for inserting the buf if necessary.
383 breakParagraphConservative(buffer.params(), pars, pit, pos);
387 pars.insert(boost::next(pars.begin(), pit),
391 // merge the empty par with the last par of the insertion
392 mergeParagraph(buffer.params(), pars,
393 pit + insertion.size() - 1);
395 pars.insert(boost::next(pars.begin(), pit + 1),
399 // merge the first par of the insertion with the current par
400 mergeParagraph(buffer.params(), pars, pit);
403 // Store the new cursor position.
404 pit_type last_paste = pit + insertion.size() - 1;
405 pit_type startpit = pit;
407 pos = pars[last_paste].size();
409 // FIXME Should we do it here, or should we let updateBuffer() do it?
410 // Set paragraph buffers. It's important to do this right away
411 // before something calls Inset::buffer() and causes a crash.
412 for (pit_type p = startpit; p <= pit; ++p)
413 pars[p].setBuffer(const_cast<Buffer &>(buffer));
415 // Join (conditionally) last pasted paragraph with next one, i.e.,
416 // the tail of the spliced document paragraph
417 if (!empty && last_paste + 1 != pit_type(pars.size())) {
418 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
419 mergeParagraph(buffer.params(), pars, last_paste);
420 } else if (pars[last_paste + 1].empty()) {
421 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
422 mergeParagraph(buffer.params(), pars, last_paste);
423 } else if (pars[last_paste].empty()) {
424 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
425 mergeParagraph(buffer.params(), pars, last_paste);
427 pars[last_paste + 1].stripLeadingSpaces(buffer.params().track_changes);
432 return PasteReturnValue(pit, pos, need_update);
436 PitPosPair eraseSelectionHelper(BufferParams const & params,
437 ParagraphList & pars,
438 pit_type startpit, pit_type endpit,
439 int startpos, int endpos)
441 // Start of selection is really invalid.
442 if (startpit == pit_type(pars.size()) ||
443 (startpos > pars[startpit].size()))
444 return PitPosPair(endpit, endpos);
446 // Start and end is inside same paragraph
447 if (endpit == pit_type(pars.size()) || startpit == endpit) {
448 endpos -= pars[startpit].eraseChars(startpos, endpos, params.track_changes);
449 return PitPosPair(endpit, endpos);
452 for (pit_type pit = startpit; pit != endpit + 1;) {
453 pos_type const left = (pit == startpit ? startpos : 0);
454 pos_type right = (pit == endpit ? endpos : pars[pit].size() + 1);
455 bool const merge = pars[pit].isMergedOnEndOfParDeletion(params.track_changes);
457 // Logically erase only, including the end-of-paragraph character
458 pars[pit].eraseChars(left, right, params.track_changes);
460 // Separate handling of paragraph break:
461 if (merge && pit != endpit &&
463 || pars[pit].hasSameLayout(pars[endpit])
464 || pars[endpit].size() == endpos)) {
465 if (pit + 1 == endpit)
466 endpos += pars[pit].size();
467 mergeParagraph(params, pars, pit);
473 // Ensure legal cursor pos:
476 return PitPosPair(endpit, endpos);
480 void putClipboard(ParagraphList const & paragraphs,
481 DocumentClassConstPtr docclass, docstring const & plaintext)
483 // This used to need to be static to avoid a memory leak. It no longer needs
484 // to be so, but the alternative is to construct a new one of these (with a
485 // new temporary directory, etc) every time, and then to destroy it. So maybe
486 // it's worth just keeping this one around.
488 static TempFile tempfile("clipboard.internal");
489 tempfile.setAutoRemove(false);
490 static Buffer * staticbuffer = theBufferList().newInternalBuffer(
491 tempfile.name().absFileName());
493 // These two things only really need doing the first time.
494 staticbuffer->setUnnamed(true);
495 staticbuffer->inset().setBuffer(*staticbuffer);
497 // Use a clone for the complicated stuff so that we do not need to clean
498 // up in order to avoid a crash.
499 Buffer * buffer = staticbuffer->cloneBufferOnly();
500 LASSERT(buffer, return);
502 // This needs doing every time.
503 buffer->params().setDocumentClass(docclass);
505 // we will use pasteSelectionHelper to copy the paragraphs into the
506 // temporary Buffer, since it does a lot of things to fix them up.
507 DocIterator dit = doc_iterator_begin(buffer, &buffer->inset());
509 pasteSelectionHelper(dit, paragraphs, docclass, buffer, el);
511 // We don't want to produce images that are not used. Therefore,
512 // output formulas as MathML. Even if this is not understood by all
513 // applications, the number that can parse it should go up in the future.
514 buffer->params().html_math_output = BufferParams::MathML;
516 // Make sure MarkAsExporting is deleted before buffer is
518 // The Buffer is being used to export. This is necessary so that the
519 // updateMacros call will record the needed information.
520 MarkAsExporting mex(buffer);
522 buffer->updateBuffer(Buffer::UpdateMaster, OutputUpdate);
523 buffer->updateMacros();
524 buffer->updateMacroInstances(OutputUpdate);
529 if (buffer->write(oslyx))
533 odocstringstream oshtml;
534 OutputParams runparams(encodings.fromLyXName("utf8"));
535 // We do not need to produce images, etc.
536 runparams.dryrun = true;
537 // We are not interested in errors (bug 8866)
538 runparams.silent = true;
539 buffer->writeLyXHTMLSource(oshtml, runparams, Buffer::FullSource);
541 theClipboard().put(lyx, oshtml.str(), plaintext);
549 /// return true if the whole ParagraphList is deleted
550 static bool isFullyDeleted(ParagraphList const & pars)
552 pit_type const pars_size = static_cast<pit_type>(pars.size());
554 // check all paragraphs
555 for (pit_type pit = 0; pit < pars_size; ++pit) {
556 if (!pars[pit].empty()) // prevent assertion failure
557 if (!pars[pit].isDeleted(0, pars[pit].size()))
564 void copySelectionHelper(Buffer const & buf, Text const & text,
565 pit_type startpit, pit_type endpit,
566 int start, int end, DocumentClassConstPtr dc, CutStack & cutstack)
568 ParagraphList const & pars = text.paragraphs();
570 // In most of these cases, we can try to recover.
571 LASSERT(0 <= start, start = 0);
572 LASSERT(start <= pars[startpit].size(), start = pars[startpit].size());
573 LASSERT(0 <= end, end = 0);
574 LASSERT(end <= pars[endpit].size(), end = pars[endpit].size());
575 LASSERT(startpit != endpit || start <= end, return);
577 // Clone the paragraphs within the selection.
578 ParagraphList copy_pars(boost::next(pars.begin(), startpit),
579 boost::next(pars.begin(), endpit + 1));
581 // Remove the end of the last paragraph; afterwards, remove the
582 // beginning of the first paragraph. Keep this order - there may only
583 // be one paragraph! Do not track deletions here; this is an internal
584 // action not visible to the user
586 Paragraph & back = copy_pars.back();
587 back.eraseChars(end, back.size(), false);
588 Paragraph & front = copy_pars.front();
589 front.eraseChars(0, start, false);
591 ParagraphList::iterator it = copy_pars.begin();
592 ParagraphList::iterator it_end = copy_pars.end();
594 for (; it != it_end; ++it) {
595 // Since we have a copy of the paragraphs, the insets
596 // do not have a proper buffer reference. It makes
597 // sense to add them temporarily, because the
598 // operations below depend on that (acceptChanges included).
599 it->setBuffer(const_cast<Buffer &>(buf));
600 // PassThru paragraphs have the Language
601 // latex_language. This is invalid for others, so we
602 // need to change it to the buffer language.
603 if (it->isPassThru())
604 it->changeLanguage(buf.params(),
605 latex_language, buf.language());
608 // do not copy text (also nested in insets) which is marked as
609 // deleted, unless the whole selection was deleted
610 if (!isFullyDeleted(copy_pars))
611 acceptChanges(copy_pars, buf.params());
613 rejectChanges(copy_pars, buf.params());
616 // do some final cleanup now, to make sure that the paragraphs
617 // are not linked to something else.
618 it = copy_pars.begin();
619 for (; it != it_end; ++it) {
620 it->setBuffer(*static_cast<Buffer *>(0));
621 it->setInsetOwner(0);
624 cutstack.push(make_pair(copy_pars, dc));
634 void region(CursorSlice const & i1, CursorSlice const & i2,
635 Inset::row_type & r1, Inset::row_type & r2,
636 Inset::col_type & c1, Inset::col_type & c2)
638 Inset & p = i1.inset();
639 c1 = p.col(i1.idx());
640 c2 = p.col(i2.idx());
643 r1 = p.row(i1.idx());
644 r2 = p.row(i2.idx());
650 docstring grabAndEraseSelection(Cursor & cur)
652 if (!cur.selection())
654 docstring res = grabSelection(cur);
660 bool reduceSelectionToOneCell(Cursor & cur)
662 if (!cur.selection() || !cur.inMathed())
665 CursorSlice i1 = cur.selBegin();
666 CursorSlice i2 = cur.selEnd();
667 if (!i1.inset().asInsetMath())
670 // the easy case: do nothing if only one cell is selected
671 if (i1.idx() == i2.idx())
676 cur.top().pos() = cur.top().lastpos();
682 bool multipleCellsSelected(Cursor const & cur)
684 if (!cur.selection() || !cur.inMathed())
687 CursorSlice i1 = cur.selBegin();
688 CursorSlice i2 = cur.selEnd();
689 if (!i1.inset().asInsetMath())
692 if (i1.idx() == i2.idx())
699 void switchBetweenClasses(DocumentClassConstPtr oldone,
700 DocumentClassConstPtr newone, InsetText & in, ErrorList & errorlist)
704 LBUFERR(!in.paragraphs().empty());
705 if (oldone == newone)
708 DocumentClass const & oldtc = *oldone;
709 DocumentClass const & newtc = *newone;
712 ParIterator it = par_iterator_begin(in);
713 ParIterator end = par_iterator_end(in);
714 // for remembering which layouts we've had to add
715 set<docstring> newlayouts;
716 for (; it != end; ++it) {
717 docstring const name = it->layout().name();
719 // the pasted text will keep their own layout name. If this layout does
720 // not exist in the new document, it will behave like a standard layout.
721 bool const added_one = newtc.addLayoutIfNeeded(name);
723 newlayouts.insert(name);
725 if (added_one || newlayouts.find(name) != newlayouts.end()) {
727 docstring const s = bformat(_("Layout `%1$s' was not found."), name);
729 ErrorItem(_("Layout Not Found"), s, it->id(), 0, it->size()));
732 if (in.usePlainLayout())
733 it->setLayout(newtc.plainLayout());
735 it->setLayout(newtc[name]);
739 InsetIterator const i_end = inset_iterator_end(in);
740 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
741 if (it->lyxCode() != FLEX_CODE)
742 // FIXME: Should we verify all InsetCollapsable?
745 docstring const layoutName = it->layoutName();
746 docstring const & n = newone->insetLayout(layoutName).name();
747 bool const is_undefined = n.empty() ||
748 n == DocumentClass::plainInsetLayout().name();
752 // The flex inset is undefined in newtc
753 docstring const oldname = from_utf8(oldtc.name());
754 docstring const newname = from_utf8(newtc.name());
756 if (oldname == newname)
757 s = bformat(_("Flex inset %1$s is undefined after "
758 "reloading `%2$s' layout."), layoutName, oldname);
760 s = bformat(_("Flex inset %1$s is undefined because of "
761 "conversion from `%2$s' layout to `%3$s'."),
762 layoutName, oldname, newname);
763 // To warn the user that something had to be done.
764 errorlist.push_back(ErrorItem(
765 _("Undefined flex inset"),
766 s, it.paragraph().id(), it.pos(), it.pos() + 1));
771 vector<docstring> availableSelections(Buffer const * buf)
773 vector<docstring> selList;
777 CutStack::const_iterator cit = theCuts.begin();
778 CutStack::const_iterator end = theCuts.end();
779 for (; cit != end; ++cit) {
780 // we do not use cit-> here because gcc 2.9x does not
782 ParagraphList const & pars = (*cit).first;
784 ParagraphList::const_iterator pit = pars.begin();
785 ParagraphList::const_iterator pend = pars.end();
786 for (; pit != pend; ++pit) {
787 Paragraph par(*pit, 0, 26);
788 // adapt paragraph to current buffer.
789 par.setBuffer(const_cast<Buffer &>(*buf));
790 asciiSel += par.asString(AS_STR_INSETS);
791 if (asciiSel.size() > 25) {
792 asciiSel.replace(22, docstring::npos,
798 selList.push_back(asciiSel);
805 size_type numberOfSelections()
807 return theCuts.size();
811 void cutSelection(Cursor & cur, bool doclear, bool realcut)
813 // This doesn't make sense, if there is no selection
814 if (!cur.selection())
817 // OK, we have a selection. This is always between cur.selBegin()
820 if (cur.inTexted()) {
821 Text * text = cur.text();
826 // make sure that the depth behind the selection are restored, too
827 cur.recordUndoSelection();
828 pit_type begpit = cur.selBegin().pit();
829 pit_type endpit = cur.selEnd().pit();
831 int endpos = cur.selEnd().pos();
833 BufferParams const & bp = cur.buffer()->params();
835 copySelectionHelper(*cur.buffer(),
838 cur.selBegin().pos(), endpos,
839 bp.documentClassPtr(), theCuts);
840 // Stuff what we got on the clipboard.
841 // Even if there is no selection.
842 putClipboard(theCuts[0].first, theCuts[0].second,
843 cur.selectionAsString(true));
846 if (begpit != endpit)
847 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
849 boost::tie(endpit, endpos) =
850 eraseSelectionHelper(bp,
853 cur.selBegin().pos(), endpos);
855 // cutSelection can invalidate the cursor so we need to set
857 // we prefer the end for when tracking changes
861 // sometimes necessary
863 && text->paragraphs()[begpit].stripLeadingSpaces(bp.track_changes))
866 // need a valid cursor. (Lgb)
867 cur.clearSelection();
869 // After a cut operation, we must make sure that the Buffer is updated
870 // because some further operation might need updated label information for
871 // example. So we cannot just use "cur.forceBufferUpdate()" here.
873 cur.buffer()->updateBuffer();
875 // tell tabular that a recent copy happened
876 dirtyTabularStack(false);
879 if (cur.inMathed()) {
880 if (cur.selBegin().idx() != cur.selEnd().idx()) {
881 // The current selection spans more than one cell.
883 cur.recordUndoInset();
885 // Record only the current cell to avoid a jumping
896 void copySelection(Cursor const & cur)
898 copySelection(cur, cur.selectionAsString(true));
902 void copyInset(Cursor const & cur, Inset * inset, docstring const & plaintext)
906 BufferParams const & bp = cur.buffer()->params();
907 par.setLayout(bp.documentClass().plainLayout());
908 Font font(inherit_font, bp.language);
909 par.insertInset(0, inset, font, Change(Change::UNCHANGED));
911 theCuts.push(make_pair(pars, bp.documentClassPtr()));
913 // stuff the selection onto the X clipboard, from an explicit copy request
914 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
920 void copySelectionToStack(Cursor const & cur, CutStack & cutstack)
922 // this doesn't make sense, if there is no selection
923 if (!cur.selection())
926 // copySelection can not yet handle the case of cross idx selection
927 if (cur.selBegin().idx() != cur.selEnd().idx())
930 if (cur.inTexted()) {
931 Text * text = cur.text();
933 // ok we have a selection. This is always between cur.selBegin()
934 // and sel_end cursor
936 // copy behind a space if there is one
937 ParagraphList & pars = text->paragraphs();
938 pos_type pos = cur.selBegin().pos();
939 pit_type par = cur.selBegin().pit();
940 while (pos < pars[par].size() &&
941 pars[par].isLineSeparator(pos) &&
942 (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
945 copySelectionHelper(*cur.buffer(), *text, par, cur.selEnd().pit(),
946 pos, cur.selEnd().pos(),
947 cur.buffer()->params().documentClassPtr(), cutstack);
949 // Reset the dirty_tabular_stack_ flag only when something
950 // is copied to the clipboard (not to the selectionBuffer).
951 if (&cutstack == &theCuts)
952 dirtyTabularStack(false);
955 if (cur.inMathed()) {
956 //lyxerr << "copySelection in mathed" << endl;
959 BufferParams const & bp = cur.buffer()->params();
960 // FIXME This should be the plain layout...right?
961 par.setLayout(bp.documentClass().plainLayout());
962 par.insert(0, grabSelection(cur), Font(), Change(Change::UNCHANGED));
964 cutstack.push(make_pair(pars, bp.documentClassPtr()));
971 void copySelectionToStack()
973 if (!selectionBuffer.empty())
974 theCuts.push(selectionBuffer[0]);
978 void copySelection(Cursor const & cur, docstring const & plaintext)
980 // In tablemode, because copy and paste actually use special table stack
981 // we do not attempt to get selected paragraphs under cursor. Instead, a
982 // paragraph with the plain text version is generated so that table cells
983 // can be pasted as pure text somewhere else.
984 if (cur.selBegin().idx() != cur.selEnd().idx()) {
987 BufferParams const & bp = cur.buffer()->params();
988 par.setLayout(bp.documentClass().plainLayout());
989 par.insert(0, plaintext, Font(), Change(Change::UNCHANGED));
991 theCuts.push(make_pair(pars, bp.documentClassPtr()));
993 copySelectionToStack(cur, theCuts);
996 // stuff the selection onto the X clipboard, from an explicit copy request
997 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
1001 void saveSelection(Cursor const & cur)
1003 // This function is called, not when a selection is formed, but when
1004 // a selection is cleared. Therefore, multiple keyboard selection
1005 // will not repeatively trigger this function (bug 3877).
1007 && cur.selBegin() == cur.bv().cursor().selBegin()
1008 && cur.selEnd() == cur.bv().cursor().selEnd()) {
1009 LYXERR(Debug::SELECTION, "saveSelection: '" << cur.selectionAsString(true) << "'");
1010 copySelectionToStack(cur, selectionBuffer);
1017 return !selectionBuffer.empty();
1021 void clearSelection()
1023 selectionBuffer.clear();
1027 void clearCutStack()
1033 docstring selection(size_t sel_index)
1035 return sel_index < theCuts.size()
1036 ? theCuts[sel_index].first.back().asString(AS_STR_INSETS | AS_STR_NEWLINES)
1041 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
1042 DocumentClassConstPtr docclass, ErrorList & errorList)
1044 if (cur.inTexted()) {
1045 Text * text = cur.text();
1048 PasteReturnValue prv =
1049 pasteSelectionHelper(cur, parlist, docclass, 0, errorList);
1050 cur.forceBufferUpdate();
1051 cur.clearSelection();
1052 text->setCursor(cur, prv.par, prv.pos);
1055 // mathed is handled in InsetMathNest/InsetMathGrid
1056 LATTEST(!cur.inMathed());
1060 bool pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
1062 // this does not make sense, if there is nothing to paste
1063 if (!checkPastePossible(sel_index))
1067 pasteParagraphList(cur, theCuts[sel_index].first,
1068 theCuts[sel_index].second, errorList);
1073 bool pasteClipboardText(Cursor & cur, ErrorList & errorList, bool asParagraphs,
1074 Clipboard::TextType type)
1076 // Use internal clipboard if it is the most recent one
1077 // This overrides asParagraphs and type on purpose!
1078 if (theClipboard().isInternal())
1079 return pasteFromStack(cur, errorList, 0);
1081 // First try LyX format
1082 if ((type == Clipboard::LyXTextType ||
1083 type == Clipboard::LyXOrPlainTextType ||
1084 type == Clipboard::AnyTextType) &&
1085 theClipboard().hasTextContents(Clipboard::LyXTextType)) {
1086 string lyx = theClipboard().getAsLyX();
1088 // For some strange reason gcc 3.2 and 3.3 do not accept
1089 // Buffer buffer(string(), false);
1090 Buffer buffer("", false);
1091 buffer.setUnnamed(true);
1092 if (buffer.readString(lyx)) {
1094 pasteParagraphList(cur, buffer.paragraphs(),
1095 buffer.params().documentClassPtr(), errorList);
1101 // Then try TeX and HTML
1102 Clipboard::TextType types[2] = {Clipboard::HtmlTextType, Clipboard::LaTeXTextType};
1103 string names[2] = {"html", "latexclipboard"};
1104 for (int i = 0; i < 2; ++i) {
1105 if (type != types[i] && type != Clipboard::AnyTextType)
1107 bool available = theClipboard().hasTextContents(types[i]);
1109 // If a specific type was explicitly requested, try to
1110 // interpret plain text: The user told us that the clipboard
1111 // contents is in the desired format
1112 if (!available && type == types[i]) {
1113 types[i] = Clipboard::PlainTextType;
1114 available = theClipboard().hasTextContents(types[i]);
1118 docstring text = theClipboard().getAsText(types[i]);
1119 available = !text.empty();
1121 // For some strange reason gcc 3.2 and 3.3 do not accept
1122 // Buffer buffer(string(), false);
1123 Buffer buffer("", false);
1124 buffer.setUnnamed(true);
1125 available = buffer.importString(names[i], text, errorList);
1127 available = !buffer.paragraphs().empty();
1128 if (available && !buffer.paragraphs()[0].empty()) {
1130 pasteParagraphList(cur, buffer.paragraphs(),
1131 buffer.params().documentClassPtr(), errorList);
1138 // Then try plain text
1139 docstring const text = theClipboard().getAsText(Clipboard::PlainTextType);
1144 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1146 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1151 void pasteSimpleText(Cursor & cur, bool asParagraphs)
1154 // Use internal clipboard if it is the most recent one
1155 if (theClipboard().isInternal()) {
1156 if (!checkPastePossible(0))
1159 ParagraphList const & pars = theCuts[0].first;
1160 ParagraphList::const_iterator it = pars.begin();
1161 for (; it != pars.end(); ++it) {
1162 if (it != pars.begin())
1164 text += (*it).asString();
1166 asParagraphs = false;
1168 // Then try plain text
1169 text = theClipboard().getAsText(Clipboard::PlainTextType);
1176 cutSelection(cur, true, false);
1178 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1180 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1184 void pasteClipboardGraphics(Cursor & cur, ErrorList & /* errorList */,
1185 Clipboard::GraphicsType preferedType)
1187 LASSERT(theClipboard().hasGraphicsContents(preferedType), return);
1189 // get picture from clipboard
1190 FileName filename = theClipboard().getAsGraphics(cur, preferedType);
1191 if (filename.empty())
1194 // create inset for graphic
1195 InsetGraphics * inset = new InsetGraphics(cur.buffer());
1196 InsetGraphicsParams params;
1197 params.filename = support::DocFileName(filename.absFileName(), false);
1198 inset->setParams(params);
1204 void pasteSelection(Cursor & cur, ErrorList & errorList)
1206 if (selectionBuffer.empty())
1209 pasteParagraphList(cur, selectionBuffer[0].first,
1210 selectionBuffer[0].second, errorList);
1214 void replaceSelectionWithString(Cursor & cur, docstring const & str)
1217 DocIterator selbeg = cur.selectionBegin();
1219 // Get font setting before we cut, we need a copy here, not a bare reference.
1221 selbeg.paragraph().getFontSettings(cur.buffer()->params(), selbeg.pos());
1223 // Insert the new string
1224 pos_type pos = cur.selEnd().pos();
1225 Paragraph & par = cur.selEnd().paragraph();
1226 docstring::const_iterator cit = str.begin();
1227 docstring::const_iterator end = str.end();
1228 for (; cit != end; ++cit, ++pos)
1229 par.insertChar(pos, *cit, font, cur.buffer()->params().track_changes);
1231 // Cut the selection
1232 cutSelection(cur, true, false);
1236 void replaceSelection(Cursor & cur)
1238 if (cur.selection())
1239 cutSelection(cur, true, false);
1243 void eraseSelection(Cursor & cur)
1245 //lyxerr << "cap::eraseSelection begin: " << cur << endl;
1246 CursorSlice const & i1 = cur.selBegin();
1247 CursorSlice const & i2 = cur.selEnd();
1248 if (i1.inset().asInsetMath()) {
1251 if (i1.idx() == i2.idx()) {
1252 i1.cell().erase(i1.pos(), i2.pos());
1253 // We may have deleted i1.cell(cur.pos()).
1254 // Make sure that pos is valid.
1255 if (cur.pos() > cur.lastpos())
1256 cur.pos() = cur.lastpos();
1258 InsetMath * p = i1.asInsetMath();
1259 Inset::row_type r1, r2;
1260 Inset::col_type c1, c2;
1261 region(i1, i2, r1, r2, c1, c2);
1262 for (Inset::row_type row = r1; row <= r2; ++row)
1263 for (Inset::col_type col = c1; col <= c2; ++col)
1264 p->cell(p->index(row, col)).clear();
1265 // We've deleted the whole cell. Only pos 0 is valid.
1268 // need a valid cursor. (Lgb)
1269 cur.clearSelection();
1271 lyxerr << "can't erase this selection 1" << endl;
1273 //lyxerr << "cap::eraseSelection end: " << cur << endl;
1277 void selDel(Cursor & cur)
1279 //lyxerr << "cap::selDel" << endl;
1280 if (cur.selection())
1281 eraseSelection(cur);
1285 void selClearOrDel(Cursor & cur)
1287 //lyxerr << "cap::selClearOrDel" << endl;
1288 if (lyxrc.auto_region_delete)
1291 cur.setSelection(false);
1295 docstring grabSelection(Cursor const & cur)
1297 if (!cur.selection())
1301 // grab selection by glueing multiple cells together. This is not what
1302 // we want because selections spanning multiple cells will get "&" and "\\"
1305 for (DocIterator dit = cur.selectionBegin();
1306 dit != cur.selectionEnd(); dit.forwardPos())
1307 os << asString(dit.cell());
1311 CursorSlice i1 = cur.selBegin();
1312 CursorSlice i2 = cur.selEnd();
1314 if (i1.idx() == i2.idx()) {
1315 if (i1.inset().asInsetMath()) {
1316 MathData::const_iterator it = i1.cell().begin();
1317 Buffer * buf = cur.buffer();
1318 return asString(MathData(buf, it + i1.pos(), it + i2.pos()));
1320 return from_ascii("unknown selection 1");
1324 Inset::row_type r1, r2;
1325 Inset::col_type c1, c2;
1326 region(i1, i2, r1, r2, c1, c2);
1329 if (i1.inset().asInsetMath()) {
1330 for (Inset::row_type row = r1; row <= r2; ++row) {
1333 for (Inset::col_type col = c1; col <= c2; ++col) {
1336 data += asString(i1.asInsetMath()->
1337 cell(i1.asInsetMath()->index(row, col)));
1341 data = from_ascii("unknown selection 2");
1347 void dirtyTabularStack(bool b)
1349 dirty_tabular_stack_ = b;
1353 bool tabularStackDirty()
1355 return dirty_tabular_stack_;