This more or less completes the re-implementation of this class. The
[lyx.git] / src / CutAndPaste.cpp
bloba30f40040714e0bfbdbe4642bea3f03b661db4d1
1 /**
2 * \file CutAndPaste.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Jürgen Vigna
7 * \author Lars Gullik Bjønnes
8 * \author Alfredo Braunstein
9 * \author Michael Gerz
11 * Full author contact details are available in file CREDITS.
14 #include <config.h>
16 #include "CutAndPaste.h"
18 #include "BranchList.h"
19 #include "Buffer.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "BufferView.h"
24 #include "Changes.h"
25 #include "Cursor.h"
26 #include "ErrorList.h"
27 #include "FuncCode.h"
28 #include "FuncRequest.h"
29 #include "InsetIterator.h"
30 #include "InsetList.h"
31 #include "Language.h"
32 #include "LyXFunc.h"
33 #include "LyXRC.h"
34 #include "Text.h"
35 #include "Paragraph.h"
36 #include "ParagraphParameters.h"
37 #include "ParIterator.h"
38 #include "Undo.h"
40 #include "insets/InsetBranch.h"
41 #include "insets/InsetCommand.h"
42 #include "insets/InsetFlex.h"
43 #include "insets/InsetGraphics.h"
44 #include "insets/InsetGraphicsParams.h"
45 #include "insets/InsetInclude.h"
46 #include "insets/InsetTabular.h"
48 #include "mathed/MathData.h"
49 #include "mathed/InsetMath.h"
50 #include "mathed/MathSupport.h"
52 #include "support/debug.h"
53 #include "support/docstream.h"
54 #include "support/gettext.h"
55 #include "support/limited_stack.h"
56 #include "support/lstrings.h"
58 #include "frontends/alert.h"
59 #include "frontends/Clipboard.h"
60 #include "frontends/Selection.h"
62 #include <boost/tuple/tuple.hpp>
63 #include <boost/next_prior.hpp>
65 #include <string>
67 using namespace std;
68 using namespace lyx::support;
69 using lyx::frontend::Clipboard;
71 namespace lyx {
73 namespace {
75 typedef pair<pit_type, int> PitPosPair;
77 typedef limited_stack<pair<ParagraphList, DocumentClass const *> > CutStack;
79 CutStack theCuts(10);
80 // persistent selection, cleared until the next selection
81 CutStack selectionBuffer(1);
83 // store whether the tabular stack is newer than the normal copy stack
84 // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
85 // when we (hopefully) have a one-for-all paste mechanism.
86 bool dirty_tabular_stack_ = false;
89 bool checkPastePossible(int index)
91 return size_t(index) < theCuts.size() && !theCuts[index].first.empty();
95 pair<PitPosPair, pit_type>
96 pasteSelectionHelper(Cursor & cur, ParagraphList const & parlist,
97 DocumentClass const * const oldDocClass, ErrorList & errorlist)
99 Buffer const & buffer = *cur.buffer();
100 pit_type pit = cur.pit();
101 pos_type pos = cur.pos();
102 InsetText * target_inset = cur.inset().asInsetText();
103 if (!target_inset) {
104 InsetTabular * it = cur.inset().asInsetTabular();
105 target_inset = it? it->cell(cur.idx())->asInsetText() : 0;
107 LASSERT(target_inset, return make_pair(PitPosPair(pit, pos), pit));
108 ParagraphList & pars = target_inset->paragraphs();
110 if (parlist.empty())
111 return make_pair(PitPosPair(pit, pos), pit);
113 BOOST_ASSERT (pos <= pars[pit].size());
115 // Make a copy of the CaP paragraphs.
116 ParagraphList insertion = parlist;
117 DocumentClass const * const newDocClass =
118 buffer.params().documentClassPtr();
120 // Now remove all out of the pars which is NOT allowed in the
121 // new environment and set also another font if that is required.
123 // Convert newline to paragraph break in ERT inset.
124 // This should not be here!
125 InsetCode const code = target_inset->lyxCode();
126 if (code == ERT_CODE || code == LISTINGS_CODE) {
127 for (size_t i = 0; i != insertion.size(); ++i) {
128 for (pos_type j = 0; j != insertion[i].size(); ++j) {
129 if (insertion[i].isNewline(j)) {
130 // do not track deletion of newline
131 insertion[i].eraseChar(j, false);
132 insertion[i].setInsetOwner(target_inset);
133 breakParagraphConservative(
134 buffer.params(),
135 insertion, i, j);
136 break;
142 // set the paragraphs to plain layout if necessary
143 if (cur.inset().usePlainLayout()) {
144 bool forcePlainLayout = cur.inset().forcePlainLayout();
145 Layout const & plainLayout = newDocClass->plainLayout();
146 Layout const & defaultLayout = newDocClass->defaultLayout();
147 ParagraphList::iterator const end = insertion.end();
148 ParagraphList::iterator par = insertion.begin();
149 for (; par != end; ++par) {
150 Layout const & parLayout = par->layout();
151 if (forcePlainLayout || parLayout == defaultLayout)
152 par->setLayout(plainLayout);
154 } else { // check if we need to reset from plain layout
155 Layout const & defaultLayout = newDocClass->defaultLayout();
156 Layout const & plainLayout = newDocClass->plainLayout();
157 ParagraphList::iterator const end = insertion.end();
158 ParagraphList::iterator par = insertion.begin();
159 for (; par != end; ++par) {
160 Layout const & parLayout = par->layout();
161 if (parLayout == plainLayout)
162 par->setLayout(defaultLayout);
166 InsetText in(cur.buffer());
167 // Make sure there is no class difference.
168 in.paragraphs().clear();
169 // This works without copying any paragraph data because we have
170 // a specialized swap method for ParagraphList. This is important
171 // since we store pointers to insets at some places and we don't
172 // want to invalidate them.
173 insertion.swap(in.paragraphs());
174 cap::switchBetweenClasses(oldDocClass, newDocClass, in, errorlist);
175 insertion.swap(in.paragraphs());
177 ParagraphList::iterator tmpbuf = insertion.begin();
178 int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
180 depth_type max_depth = pars[pit].getMaxDepthAfter();
182 for (; tmpbuf != insertion.end(); ++tmpbuf) {
183 // If we have a negative jump so that the depth would
184 // go below 0 depth then we have to redo the delta to
185 // this new max depth level so that subsequent
186 // paragraphs are aligned correctly to this paragraph
187 // at level 0.
188 if (int(tmpbuf->params().depth()) + depth_delta < 0)
189 depth_delta = 0;
191 // Set the right depth so that we are not too deep or shallow.
192 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
193 if (tmpbuf->params().depth() > max_depth)
194 tmpbuf->params().depth(max_depth);
196 // Only set this from the 2nd on as the 2nd depends
197 // for maxDepth still on pit.
198 if (tmpbuf != insertion.begin())
199 max_depth = tmpbuf->getMaxDepthAfter();
201 // Set the inset owner of this paragraph.
202 tmpbuf->setInsetOwner(target_inset);
203 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
204 // do not track deletion of invalid insets
205 if (Inset * inset = tmpbuf->getInset(i))
206 if (!target_inset->insetAllowed(inset->lyxCode()))
207 tmpbuf->eraseChar(i--, false);
210 tmpbuf->setChange(Change(buffer.params().trackChanges ?
211 Change::INSERTED : Change::UNCHANGED));
214 bool const empty = pars[pit].empty();
215 if (!empty) {
216 // Make the buf exactly the same layout as the cursor
217 // paragraph.
218 insertion.begin()->makeSameLayout(pars[pit]);
221 // Prepare the paragraphs and insets for insertion.
222 insertion.swap(in.paragraphs());
224 InsetIterator const i_end = inset_iterator_end(in);
225 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
226 // Even though this will also be done later, it has to be done here
227 // since, e.g., InsetLabel::updateCommand() is going to try to access
228 // the buffer() member.
229 it->setBuffer(const_cast<Buffer &>(buffer));
230 switch (it->lyxCode()) {
232 case LABEL_CODE: {
233 // check for duplicates
234 InsetCommand & lab = static_cast<InsetCommand &>(*it);
235 docstring const oldname = lab.getParam("name");
236 lab.updateCommand(oldname, false);
237 docstring const newname = lab.getParam("name");
238 if (oldname != newname) {
239 // adapt the references
240 for (InsetIterator itt = inset_iterator_begin(in); itt != i_end; ++itt) {
241 if (itt->lyxCode() == REF_CODE) {
242 InsetCommand & ref = dynamic_cast<InsetCommand &>(*itt);
243 if (ref.getParam("reference") == oldname)
244 ref.setParam("reference", newname);
248 break;
251 case INCLUDE_CODE: {
252 InsetInclude & inc = static_cast<InsetInclude &>(*it);
253 inc.updateCommand();
254 break;
257 case BIBITEM_CODE: {
258 // check for duplicates
259 InsetCommand & bib = static_cast<InsetCommand &>(*it);
260 docstring const oldkey = bib.getParam("key");
261 bib.updateCommand(oldkey, false);
262 docstring const newkey = bib.getParam("key");
263 if (oldkey != newkey) {
264 // adapt the references
265 for (InsetIterator itt = inset_iterator_begin(in); itt != i_end; ++itt) {
266 if (itt->lyxCode() == CITE_CODE) {
267 InsetCommand & ref = dynamic_cast<InsetCommand &>(*itt);
268 if (ref.getParam("key") == oldkey)
269 ref.setParam("key", newkey);
273 break;
276 case BRANCH_CODE: {
277 // check if branch is known to target buffer
278 // or its master
279 InsetBranch & br = static_cast<InsetBranch &>(*it);
280 docstring const name = br.branch();
281 if (name.empty())
282 break;
283 bool const is_child = (&buffer != buffer.masterBuffer());
284 BranchList branchlist = buffer.params().branchlist();
285 if ((!is_child && branchlist.find(name))
286 || (is_child && (branchlist.find(name)
287 || buffer.masterBuffer()->params().branchlist().find(name))))
288 break;
289 // FIXME: add an option to add the branch to the master's BranchList.
290 docstring text = bformat(
291 _("The pasted branch \"%1$s\" is undefined.\n"
292 "Do you want to add it to the document's branch list?"),
293 name);
294 if (frontend::Alert::prompt(_("Unknown branch"),
295 text, 0, 1, _("&Add"), _("&Don't Add")) != 0)
296 break;
297 lyx::dispatch(FuncRequest(LFUN_BRANCH_ADD, name));
298 break;
301 default:
302 break; // nothing
305 insertion.swap(in.paragraphs());
307 // Split the paragraph for inserting the buf if necessary.
308 if (!empty)
309 breakParagraphConservative(buffer.params(), pars, pit, pos);
311 // Paste it!
312 if (empty) {
313 pars.insert(boost::next(pars.begin(), pit),
314 insertion.begin(),
315 insertion.end());
317 // merge the empty par with the last par of the insertion
318 mergeParagraph(buffer.params(), pars,
319 pit + insertion.size() - 1);
320 } else {
321 pars.insert(boost::next(pars.begin(), pit + 1),
322 insertion.begin(),
323 insertion.end());
325 // merge the first par of the insertion with the current par
326 mergeParagraph(buffer.params(), pars, pit);
329 // Store the new cursor position.
330 pit_type last_paste = pit + insertion.size() - 1;
331 pit_type startpit = pit;
332 pit = last_paste;
333 pos = pars[last_paste].size();
335 // FIXME Should we do it here, or should we let updateLabels() do it?
336 // Set paragraph buffers. It's important to do this right away
337 // before something calls Inset::buffer() and causes a crash.
338 for (pit_type p = startpit; p <= pit; ++p)
339 pars[p].setBuffer(const_cast<Buffer &>(buffer));
341 // Join (conditionally) last pasted paragraph with next one, i.e.,
342 // the tail of the spliced document paragraph
343 if (!empty && last_paste + 1 != pit_type(pars.size())) {
344 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
345 mergeParagraph(buffer.params(), pars, last_paste);
346 } else if (pars[last_paste + 1].empty()) {
347 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
348 mergeParagraph(buffer.params(), pars, last_paste);
349 } else if (pars[last_paste].empty()) {
350 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
351 mergeParagraph(buffer.params(), pars, last_paste);
352 } else {
353 pars[last_paste + 1].stripLeadingSpaces(buffer.params().trackChanges);
354 ++last_paste;
358 return make_pair(PitPosPair(pit, pos), last_paste + 1);
362 PitPosPair eraseSelectionHelper(BufferParams const & params,
363 ParagraphList & pars,
364 pit_type startpit, pit_type endpit,
365 int startpos, int endpos)
367 // Start of selection is really invalid.
368 if (startpit == pit_type(pars.size()) ||
369 (startpos > pars[startpit].size()))
370 return PitPosPair(endpit, endpos);
372 // Start and end is inside same paragraph
373 if (endpit == pit_type(pars.size()) || startpit == endpit) {
374 endpos -= pars[startpit].eraseChars(startpos, endpos, params.trackChanges);
375 return PitPosPair(endpit, endpos);
378 for (pit_type pit = startpit; pit != endpit + 1;) {
379 pos_type const left = (pit == startpit ? startpos : 0);
380 pos_type right = (pit == endpit ? endpos : pars[pit].size() + 1);
381 bool const merge = pars[pit].isMergedOnEndOfParDeletion(params.trackChanges);
383 // Logically erase only, including the end-of-paragraph character
384 pars[pit].eraseChars(left, right, params.trackChanges);
386 // Separate handling of paragraph break:
387 if (merge && pit != endpit &&
388 (pit + 1 != endpit
389 || pars[pit].hasSameLayout(pars[endpit])
390 || pars[endpit].size() == endpos)) {
391 if (pit + 1 == endpit)
392 endpos += pars[pit].size();
393 mergeParagraph(params, pars, pit);
394 --endpit;
395 } else
396 ++pit;
399 // Ensure legal cursor pos:
400 endpit = startpit;
401 endpos = startpos;
402 return PitPosPair(endpit, endpos);
406 void putClipboard(ParagraphList const & paragraphs,
407 DocumentClass const * const docclass, docstring const & plaintext)
409 // For some strange reason gcc 3.2 and 3.3 do not accept
410 // Buffer buffer(string(), false);
411 // This needs to be static to avoid a memory leak. When a Buffer is
412 // constructed, it constructs a BufferParams, which in turn constructs
413 // a DocumentClass, via new, that is never deleted. If we were to go to
414 // some kind of garbage collection there, or a shared_ptr, then this
415 // would not be needed.
416 static Buffer * buffer = theBufferList().newBuffer(
417 FileName::tempName().absFilename() + "_clipboard.internal");
418 buffer->setUnnamed(true);
419 buffer->paragraphs() = paragraphs;
420 buffer->inset().setBuffer(*buffer);
421 buffer->params().setDocumentClass(docclass);
422 ostringstream lyx;
423 if (buffer->write(lyx))
424 theClipboard().put(lyx.str(), plaintext);
425 else
426 theClipboard().put(string(), plaintext);
427 // Save that memory
428 buffer->paragraphs().clear();
432 /// return true if the whole ParagraphList is deleted
433 static bool isFullyDeleted(ParagraphList const & pars)
435 pit_type const pars_size = static_cast<pit_type>(pars.size());
437 // check all paragraphs
438 for (pit_type pit = 0; pit < pars_size; ++pit) {
439 if (!pars[pit].empty()) // prevent assertion failure
440 if (!pars[pit].isDeleted(0, pars[pit].size()))
441 return false;
443 return true;
447 void copySelectionHelper(Buffer const & buf, Text const & text,
448 pit_type startpit, pit_type endpit,
449 int start, int end, DocumentClass const * const dc, CutStack & cutstack)
451 ParagraphList const & pars = text.paragraphs();
453 LASSERT(0 <= start && start <= pars[startpit].size(), /**/);
454 LASSERT(0 <= end && end <= pars[endpit].size(), /**/);
455 LASSERT(startpit != endpit || start <= end, /**/);
457 // Clone the paragraphs within the selection.
458 ParagraphList copy_pars(boost::next(pars.begin(), startpit),
459 boost::next(pars.begin(), endpit + 1));
461 // Remove the end of the last paragraph; afterwards, remove the
462 // beginning of the first paragraph. Keep this order - there may only
463 // be one paragraph! Do not track deletions here; this is an internal
464 // action not visible to the user
466 Paragraph & back = copy_pars.back();
467 back.eraseChars(end, back.size(), false);
468 Paragraph & front = copy_pars.front();
469 front.eraseChars(0, start, false);
471 ParagraphList::iterator it = copy_pars.begin();
472 ParagraphList::iterator it_end = copy_pars.end();
474 for (; it != it_end; it++) {
475 // Since we have a copy of the paragraphs, the insets
476 // do not have a proper buffer reference. It makes
477 // sense to add them temporarily, because the
478 // operations below depend on that (acceptChanges included).
479 it->setBuffer(const_cast<Buffer &>(buf));
480 // PassThru paragraphs have the Language
481 // latex_language. This is invalid for others, so we
482 // need to change it to the buffer language.
483 if (text.inset().getLayout().isPassThru())
484 it->changeLanguage(buf.params(),
485 latex_language, buf.language());
488 // do not copy text (also nested in insets) which is marked as
489 // deleted, unless the whole selection was deleted
490 if (!isFullyDeleted(copy_pars))
491 acceptChanges(copy_pars, buf.params());
494 // do some final cleanup now, to make sure that the paragraphs
495 // are not linked to something else.
496 it = copy_pars.begin();
497 for (; it != it_end; it++) {
498 it->setBuffer(*static_cast<Buffer *>(0));
499 it->setInsetOwner(0);
502 DocumentClass * d = const_cast<DocumentClass *>(dc);
503 cutstack.push(make_pair(copy_pars, d));
506 } // namespace anon
511 namespace cap {
513 void region(CursorSlice const & i1, CursorSlice const & i2,
514 Inset::row_type & r1, Inset::row_type & r2,
515 Inset::col_type & c1, Inset::col_type & c2)
517 Inset & p = i1.inset();
518 c1 = p.col(i1.idx());
519 c2 = p.col(i2.idx());
520 if (c1 > c2)
521 swap(c1, c2);
522 r1 = p.row(i1.idx());
523 r2 = p.row(i2.idx());
524 if (r1 > r2)
525 swap(r1, r2);
529 docstring grabAndEraseSelection(Cursor & cur)
531 if (!cur.selection())
532 return docstring();
533 docstring res = grabSelection(cur);
534 eraseSelection(cur);
535 return res;
539 bool reduceSelectionToOneCell(Cursor & cur)
541 if (!cur.selection() || !cur.inMathed())
542 return false;
544 CursorSlice i1 = cur.selBegin();
545 CursorSlice i2 = cur.selEnd();
546 if (!i1.inset().asInsetMath())
547 return false;
549 // the easy case: do nothing if only one cell is selected
550 if (i1.idx() == i2.idx())
551 return true;
553 cur.top().pos() = 0;
554 cur.resetAnchor();
555 cur.top().pos() = cur.top().lastpos();
557 return true;
561 bool multipleCellsSelected(Cursor const & cur)
563 if (!cur.selection() || !cur.inMathed())
564 return false;
566 CursorSlice i1 = cur.selBegin();
567 CursorSlice i2 = cur.selEnd();
568 if (!i1.inset().asInsetMath())
569 return false;
571 if (i1.idx() == i2.idx())
572 return false;
574 return true;
578 void switchBetweenClasses(DocumentClass const * const oldone,
579 DocumentClass const * const newone, InsetText & in, ErrorList & errorlist)
581 errorlist.clear();
583 LASSERT(!in.paragraphs().empty(), /**/);
584 if (oldone == newone)
585 return;
587 DocumentClass const & oldtc = *oldone;
588 DocumentClass const & newtc = *newone;
590 // layouts
591 ParIterator end = par_iterator_end(in);
592 for (ParIterator it = par_iterator_begin(in); it != end; ++it) {
593 docstring const name = it->layout().name();
595 // the pasted text will keep their own layout name. If this layout does
596 // not exist in the new document, it will behave like a standard layout.
597 newtc.addLayoutIfNeeded(name);
599 if (in.usePlainLayout())
600 it->setLayout(newtc.plainLayout());
601 else
602 it->setLayout(newtc[name]);
605 // character styles
606 InsetIterator const i_end = inset_iterator_end(in);
607 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
608 if (it->lyxCode() != FLEX_CODE)
609 // FIXME: Should we verify all InsetCollapsable?
610 continue;
611 docstring const & n = newone->insetLayout(it->name()).name();
612 bool const is_undefined = n.empty() ||
613 n == DocumentClass::plainInsetLayout().name();
614 if (!is_undefined)
615 continue;
616 // The flex inset is undefined in newtc
617 docstring const s = bformat(_(
618 "Flex inset %1$s is "
619 "undefined because of class "
620 "conversion from\n%2$s to %3$s"),
621 it->name(), from_utf8(oldtc.name()),
622 from_utf8(newtc.name()));
623 // To warn the user that something had to be done.
624 errorlist.push_back(ErrorItem(
625 _("Undefined flex inset"),
626 s, it.paragraph().id(), it.pos(), it.pos() + 1));
631 vector<docstring> availableSelections(Buffer const * buf)
633 vector<docstring> selList;
634 if (!buf)
635 return selList;
637 CutStack::const_iterator cit = theCuts.begin();
638 CutStack::const_iterator end = theCuts.end();
639 for (; cit != end; ++cit) {
640 // we do not use cit-> here because gcc 2.9x does not
641 // like it (JMarc)
642 ParagraphList const & pars = (*cit).first;
643 docstring asciiSel;
644 ParagraphList::const_iterator pit = pars.begin();
645 ParagraphList::const_iterator pend = pars.end();
646 for (; pit != pend; ++pit) {
647 Paragraph par(*pit, 0, 26);
648 // adapt paragraph to current buffer.
649 par.setBuffer(const_cast<Buffer &>(*buf));
650 asciiSel += par.asString(AS_STR_INSETS);
651 if (asciiSel.size() > 25) {
652 asciiSel.replace(22, docstring::npos,
653 from_ascii("..."));
654 break;
658 selList.push_back(asciiSel);
661 return selList;
665 size_type numberOfSelections()
667 return theCuts.size();
671 void cutSelection(Cursor & cur, bool doclear, bool realcut)
673 // This doesn't make sense, if there is no selection
674 if (!cur.selection())
675 return;
677 // OK, we have a selection. This is always between cur.selBegin()
678 // and cur.selEnd()
680 if (cur.inTexted()) {
681 Text * text = cur.text();
682 LASSERT(text, /**/);
684 saveSelection(cur);
686 // make sure that the depth behind the selection are restored, too
687 cur.recordUndoSelection();
688 pit_type begpit = cur.selBegin().pit();
689 pit_type endpit = cur.selEnd().pit();
691 int endpos = cur.selEnd().pos();
693 BufferParams const & bp = cur.buffer()->params();
694 if (realcut) {
695 copySelectionHelper(*cur.buffer(),
696 *text,
697 begpit, endpit,
698 cur.selBegin().pos(), endpos,
699 bp.documentClassPtr(), theCuts);
700 // Stuff what we got on the clipboard.
701 // Even if there is no selection.
702 putClipboard(theCuts[0].first, theCuts[0].second,
703 cur.selectionAsString(true));
706 if (begpit != endpit)
707 cur.updateFlags(Update::Force | Update::FitCursor);
709 boost::tie(endpit, endpos) =
710 eraseSelectionHelper(bp,
711 text->paragraphs(),
712 begpit, endpit,
713 cur.selBegin().pos(), endpos);
715 // cutSelection can invalidate the cursor so we need to set
716 // it anew. (Lgb)
717 // we prefer the end for when tracking changes
718 cur.pos() = endpos;
719 cur.pit() = endpit;
721 // sometimes necessary
722 if (doclear
723 && text->paragraphs()[begpit].stripLeadingSpaces(bp.trackChanges))
724 cur.fixIfBroken();
726 // need a valid cursor. (Lgb)
727 cur.clearSelection();
728 cur.buffer()->updateLabels();
730 // tell tabular that a recent copy happened
731 dirtyTabularStack(false);
734 if (cur.inMathed()) {
735 if (cur.selBegin().idx() != cur.selEnd().idx()) {
736 // The current selection spans more than one cell.
737 // Record all cells
738 cur.recordUndoInset();
739 } else {
740 // Record only the current cell to avoid a jumping
741 // cursor after undo
742 cur.recordUndo();
744 if (realcut)
745 copySelection(cur);
746 eraseSelection(cur);
751 void copySelection(Cursor const & cur)
753 copySelection(cur, cur.selectionAsString(true));
757 void copyInset(Cursor const & cur, Inset * inset, docstring const & plaintext)
759 ParagraphList pars;
760 Paragraph par;
761 BufferParams const & bp = cur.buffer()->params();
762 par.setLayout(bp.documentClass().plainLayout());
763 par.insertInset(0, inset, Change(Change::UNCHANGED));
764 pars.push_back(par);
765 theCuts.push(make_pair(pars, bp.documentClassPtr()));
767 // stuff the selection onto the X clipboard, from an explicit copy request
768 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
771 namespace {
773 void copySelectionToStack(Cursor const & cur, CutStack & cutstack)
775 // this doesn't make sense, if there is no selection
776 if (!cur.selection())
777 return;
779 // copySelection can not yet handle the case of cross idx selection
780 if (cur.selBegin().idx() != cur.selEnd().idx())
781 return;
783 if (cur.inTexted()) {
784 Text * text = cur.text();
785 LASSERT(text, /**/);
786 // ok we have a selection. This is always between cur.selBegin()
787 // and sel_end cursor
789 // copy behind a space if there is one
790 ParagraphList & pars = text->paragraphs();
791 pos_type pos = cur.selBegin().pos();
792 pit_type par = cur.selBegin().pit();
793 while (pos < pars[par].size() &&
794 pars[par].isLineSeparator(pos) &&
795 (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
796 ++pos;
798 copySelectionHelper(*cur.buffer(), *text, par, cur.selEnd().pit(),
799 pos, cur.selEnd().pos(),
800 cur.buffer()->params().documentClassPtr(), cutstack);
802 // Reset the dirty_tabular_stack_ flag only when something
803 // is copied to the clipboard (not to the selectionBuffer).
804 if (&cutstack == &theCuts)
805 dirtyTabularStack(false);
808 if (cur.inMathed()) {
809 //lyxerr << "copySelection in mathed" << endl;
810 ParagraphList pars;
811 Paragraph par;
812 BufferParams const & bp = cur.buffer()->params();
813 // FIXME This should be the plain layout...right?
814 par.setLayout(bp.documentClass().plainLayout());
815 par.insert(0, grabSelection(cur), Font(), Change(Change::UNCHANGED));
816 pars.push_back(par);
817 cutstack.push(make_pair(pars, bp.documentClassPtr()));
824 void copySelectionToStack()
826 if (!selectionBuffer.empty())
827 theCuts.push(selectionBuffer[0]);
831 void copySelection(Cursor const & cur, docstring const & plaintext)
833 // In tablemode, because copy and paste actually use special table stack
834 // we do not attempt to get selected paragraphs under cursor. Instead, a
835 // paragraph with the plain text version is generated so that table cells
836 // can be pasted as pure text somewhere else.
837 if (cur.selBegin().idx() != cur.selEnd().idx()) {
838 ParagraphList pars;
839 Paragraph par;
840 BufferParams const & bp = cur.buffer()->params();
841 par.setLayout(bp.documentClass().plainLayout());
842 par.insert(0, plaintext, Font(), Change(Change::UNCHANGED));
843 pars.push_back(par);
844 theCuts.push(make_pair(pars, bp.documentClassPtr()));
845 } else {
846 copySelectionToStack(cur, theCuts);
849 // stuff the selection onto the X clipboard, from an explicit copy request
850 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
854 void saveSelection(Cursor const & cur)
856 // This function is called, not when a selection is formed, but when
857 // a selection is cleared. Therefore, multiple keyboard selection
858 // will not repeatively trigger this function (bug 3877).
859 if (cur.selection()
860 && cur.selBegin() == cur.bv().cursor().selBegin()
861 && cur.selEnd() == cur.bv().cursor().selEnd()) {
862 LYXERR(Debug::SELECTION, "saveSelection: '" << cur.selectionAsString(true) << "'");
863 copySelectionToStack(cur, selectionBuffer);
868 bool selection()
870 return !selectionBuffer.empty();
874 void clearSelection()
876 selectionBuffer.clear();
880 void clearCutStack()
882 theCuts.clear();
886 docstring selection(size_t sel_index)
888 return sel_index < theCuts.size()
889 ? theCuts[sel_index].first.back().asString(AS_STR_INSETS | AS_STR_NEWLINES)
890 : docstring();
894 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
895 DocumentClass const * const docclass, ErrorList & errorList)
897 if (cur.inTexted()) {
898 Text * text = cur.text();
899 LASSERT(text, /**/);
901 pit_type endpit;
902 PitPosPair ppp;
904 boost::tie(ppp, endpit) =
905 pasteSelectionHelper(cur, parlist, docclass, errorList);
906 cur.buffer()->updateLabels();
907 cur.clearSelection();
908 text->setCursor(cur, ppp.first, ppp.second);
911 // mathed is handled in InsetMathNest/InsetMathGrid
912 LASSERT(!cur.inMathed(), /**/);
916 void pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
918 // this does not make sense, if there is nothing to paste
919 if (!checkPastePossible(sel_index))
920 return;
922 cur.recordUndo();
923 pasteParagraphList(cur, theCuts[sel_index].first,
924 theCuts[sel_index].second, errorList);
925 cur.setSelection();
929 void pasteClipboardText(Cursor & cur, ErrorList & errorList, bool asParagraphs)
931 // Use internal clipboard if it is the most recent one
932 if (theClipboard().isInternal()) {
933 pasteFromStack(cur, errorList, 0);
934 return;
937 // First try LyX format
938 if (theClipboard().hasLyXContents()) {
939 string lyx = theClipboard().getAsLyX();
940 if (!lyx.empty()) {
941 // For some strange reason gcc 3.2 and 3.3 do not accept
942 // Buffer buffer(string(), false);
943 Buffer buffer("", false);
944 buffer.setUnnamed(true);
945 if (buffer.readString(lyx)) {
946 cur.recordUndo();
947 pasteParagraphList(cur, buffer.paragraphs(),
948 buffer.params().documentClassPtr(), errorList);
949 cur.setSelection();
950 return;
955 // Then try plain text
956 docstring const text = theClipboard().getAsText();
957 if (text.empty())
958 return;
959 cur.recordUndo();
960 if (asParagraphs)
961 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
962 else
963 cur.text()->insertStringAsLines(cur, text, cur.current_font);
967 void pasteClipboardGraphics(Cursor & cur, ErrorList & /* errorList */,
968 Clipboard::GraphicsType preferedType)
970 LASSERT(theClipboard().hasGraphicsContents(preferedType), /**/);
972 // get picture from clipboard
973 FileName filename = theClipboard().getAsGraphics(cur, preferedType);
974 if (filename.empty())
975 return;
977 // create inset for graphic
978 InsetGraphics * inset = new InsetGraphics(cur.buffer());
979 InsetGraphicsParams params;
980 params.filename = support::DocFileName(filename.absFilename());
981 inset->setParams(params);
982 cur.recordUndo();
983 cur.insert(inset);
987 void pasteSelection(Cursor & cur, ErrorList & errorList)
989 if (selectionBuffer.empty())
990 return;
991 cur.recordUndo();
992 pasteParagraphList(cur, selectionBuffer[0].first,
993 selectionBuffer[0].second, errorList);
997 void replaceSelectionWithString(Cursor & cur, docstring const & str, bool backwards)
999 cur.recordUndo();
1000 DocIterator selbeg = cur.selectionBegin();
1002 // Get font setting before we cut, we need a copy here, not a bare reference.
1003 Font const font =
1004 selbeg.paragraph().getFontSettings(cur.buffer()->params(), selbeg.pos());
1006 // Insert the new string
1007 pos_type pos = cur.selEnd().pos();
1008 Paragraph & par = cur.selEnd().paragraph();
1009 docstring::const_iterator cit = str.begin();
1010 docstring::const_iterator end = str.end();
1011 for (; cit != end; ++cit, ++pos)
1012 par.insertChar(pos, *cit, font, cur.buffer()->params().trackChanges);
1014 // Cut the selection
1015 cutSelection(cur, true, false);
1017 // select the replacement
1018 if (backwards) {
1019 selbeg.pos() += str.length();
1020 cur.setSelection(selbeg, -int(str.length()));
1021 } else
1022 cur.setSelection(selbeg, str.length());
1026 void replaceSelection(Cursor & cur)
1028 if (cur.selection())
1029 cutSelection(cur, true, false);
1033 void eraseSelection(Cursor & cur)
1035 //lyxerr << "cap::eraseSelection begin: " << cur << endl;
1036 CursorSlice const & i1 = cur.selBegin();
1037 CursorSlice const & i2 = cur.selEnd();
1038 if (i1.inset().asInsetMath()) {
1039 saveSelection(cur);
1040 cur.top() = i1;
1041 if (i1.idx() == i2.idx()) {
1042 i1.cell().erase(i1.pos(), i2.pos());
1043 // We may have deleted i1.cell(cur.pos()).
1044 // Make sure that pos is valid.
1045 if (cur.pos() > cur.lastpos())
1046 cur.pos() = cur.lastpos();
1047 } else {
1048 InsetMath * p = i1.asInsetMath();
1049 Inset::row_type r1, r2;
1050 Inset::col_type c1, c2;
1051 region(i1, i2, r1, r2, c1, c2);
1052 for (Inset::row_type row = r1; row <= r2; ++row)
1053 for (Inset::col_type col = c1; col <= c2; ++col)
1054 p->cell(p->index(row, col)).clear();
1055 // We've deleted the whole cell. Only pos 0 is valid.
1056 cur.pos() = 0;
1058 // need a valid cursor. (Lgb)
1059 cur.clearSelection();
1060 } else {
1061 lyxerr << "can't erase this selection 1" << endl;
1063 //lyxerr << "cap::eraseSelection end: " << cur << endl;
1067 void selDel(Cursor & cur)
1069 //lyxerr << "cap::selDel" << endl;
1070 if (cur.selection())
1071 eraseSelection(cur);
1075 void selClearOrDel(Cursor & cur)
1077 //lyxerr << "cap::selClearOrDel" << endl;
1078 if (lyxrc.auto_region_delete)
1079 selDel(cur);
1080 else
1081 cur.setSelection(false);
1085 docstring grabSelection(Cursor const & cur)
1087 if (!cur.selection())
1088 return docstring();
1090 #if 0
1091 // grab selection by glueing multiple cells together. This is not what
1092 // we want because selections spanning multiple cells will get "&" and "\\"
1093 // seperators.
1094 ostringstream os;
1095 for (DocIterator dit = cur.selectionBegin();
1096 dit != cur.selectionEnd(); dit.forwardPos())
1097 os << asString(dit.cell());
1098 return os.str();
1099 #endif
1101 CursorSlice i1 = cur.selBegin();
1102 CursorSlice i2 = cur.selEnd();
1104 if (i1.idx() == i2.idx()) {
1105 if (i1.inset().asInsetMath()) {
1106 MathData::const_iterator it = i1.cell().begin();
1107 Buffer * buf = cur.buffer();
1108 return asString(MathData(buf, it + i1.pos(), it + i2.pos()));
1109 } else {
1110 return from_ascii("unknown selection 1");
1114 Inset::row_type r1, r2;
1115 Inset::col_type c1, c2;
1116 region(i1, i2, r1, r2, c1, c2);
1118 docstring data;
1119 if (i1.inset().asInsetMath()) {
1120 for (Inset::row_type row = r1; row <= r2; ++row) {
1121 if (row > r1)
1122 data += "\\\\";
1123 for (Inset::col_type col = c1; col <= c2; ++col) {
1124 if (col > c1)
1125 data += '&';
1126 data += asString(i1.asInsetMath()->
1127 cell(i1.asInsetMath()->index(row, col)));
1130 } else {
1131 data = from_ascii("unknown selection 2");
1133 return data;
1137 void dirtyTabularStack(bool b)
1139 dirty_tabular_stack_ = b;
1143 bool tabularStackDirty()
1145 return dirty_tabular_stack_;
1149 } // namespace cap
1150 } // namespace lyx