]> git.lyx.org Git - lyx.git/blob - src/CutAndPaste.cpp
bfce241918a7b2be9d587eed8f253e9209c0e168
[lyx.git] / src / CutAndPaste.cpp
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.
5  *
6  * \author Jürgen Vigna
7  * \author Lars Gullik Bjønnes
8  * \author Alfredo Braunstein
9  * \author Michael Gerz
10  *
11  * Full author contact details are available in file CREDITS.
12  */
13
14 #include <config.h>
15
16 #include "CutAndPaste.h"
17
18 #include "Buffer.h"
19 #include "buffer_funcs.h"
20 #include "BufferList.h"
21 #include "BufferParams.h"
22 #include "BufferView.h"
23 #include "Changes.h"
24 #include "Cursor.h"
25 #include "ErrorList.h"
26 #include "FuncCode.h"
27 #include "FuncRequest.h"
28 #include "InsetIterator.h"
29 #include "InsetList.h"
30 #include "Language.h"
31 #include "LyXFunc.h"
32 #include "LyXRC.h"
33 #include "Text.h"
34 #include "Paragraph.h"
35 #include "paragraph_funcs.h"
36 #include "ParagraphParameters.h"
37 #include "ParIterator.h"
38 #include "Undo.h"
39
40 #include "insets/InsetFlex.h"
41 #include "insets/InsetCommand.h"
42 #include "insets/InsetGraphics.h"
43 #include "insets/InsetGraphicsParams.h"
44 #include "insets/InsetTabular.h"
45
46 #include "mathed/MathData.h"
47 #include "mathed/InsetMath.h"
48 #include "mathed/MathSupport.h"
49
50 #include "support/debug.h"
51 #include "support/docstream.h"
52 #include "support/gettext.h"
53 #include "support/limited_stack.h"
54 #include "support/lstrings.h"
55
56 #include "frontends/Clipboard.h"
57 #include "frontends/Selection.h"
58
59 #include <boost/tuple/tuple.hpp>
60 #include <boost/next_prior.hpp>
61
62 #include <string>
63
64 using namespace std;
65 using namespace lyx::support;
66 using lyx::frontend::Clipboard;
67
68 namespace lyx {
69
70 namespace {
71
72 typedef pair<pit_type, int> PitPosPair;
73
74 typedef limited_stack<pair<ParagraphList, DocumentClass const *> > CutStack;
75
76 CutStack theCuts(10);
77 // persistent selection, cleared until the next selection
78 CutStack selectionBuffer(1);
79
80 // store whether the tabular stack is newer than the normal copy stack
81 // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
82 // when we (hopefully) have a one-for-all paste mechanism.
83 bool dirty_tabular_stack_ = false;
84
85
86 bool checkPastePossible(int index)
87 {
88         return size_t(index) < theCuts.size() && !theCuts[index].first.empty();
89 }
90
91
92 pair<PitPosPair, pit_type>
93 pasteSelectionHelper(Cursor & cur, ParagraphList const & parlist,
94                      DocumentClass const * const oldDocClass, ErrorList & errorlist)
95 {
96         Buffer const & buffer = *cur.buffer();
97         pit_type pit = cur.pit();
98         pos_type pos = cur.pos();
99         InsetText * target_inset = cur.inset().asInsetText();
100         if (!target_inset) {
101                 InsetTabular * it = cur.inset().asInsetTabular();
102                 target_inset = it? it->cell(cur.idx())->asInsetText() : 0;
103         }
104         LASSERT(target_inset, return make_pair(PitPosPair(pit, pos), pit));
105         ParagraphList & pars = target_inset->paragraphs();
106
107         if (parlist.empty())
108                 return make_pair(PitPosPair(pit, pos), pit);
109
110         BOOST_ASSERT (pos <= pars[pit].size());
111
112         // Make a copy of the CaP paragraphs.
113         ParagraphList insertion = parlist;
114         DocumentClass const * const newDocClass = 
115                 buffer.params().documentClassPtr();
116
117         // Now remove all out of the pars which is NOT allowed in the
118         // new environment and set also another font if that is required.
119
120         // Convert newline to paragraph break in ERT inset.
121         // This should not be here!
122         InsetCode const code = target_inset->lyxCode();
123         if (code == ERT_CODE || code == LISTINGS_CODE) {
124                 for (size_t i = 0; i != insertion.size(); ++i) {
125                         for (pos_type j = 0; j != insertion[i].size(); ++j) {
126                                 if (insertion[i].isNewline(j)) {
127                                         // do not track deletion of newline
128                                         insertion[i].eraseChar(j, false);
129                                         insertion[i].setInsetOwner(target_inset);
130                                         breakParagraphConservative(
131                                                         buffer.params(),
132                                                         insertion, i, j);
133                                         break;
134                                 }
135                         }
136                 }
137         }
138
139         // set the paragraphs to plain layout if necessary
140         if (cur.inset().usePlainLayout()) {
141                 bool forcePlainLayout = cur.inset().forcePlainLayout();
142                 Layout const & plainLayout = newDocClass->plainLayout();
143                 Layout const & defaultLayout = newDocClass->defaultLayout();
144                 ParagraphList::iterator const end = insertion.end();
145                 ParagraphList::iterator par = insertion.begin();
146                 for (; par != end; ++par) {
147                         Layout const & parLayout = par->layout();
148                         if (forcePlainLayout || parLayout == defaultLayout)
149                                 par->setLayout(plainLayout);
150                 }
151         } else { // check if we need to reset from plain layout
152                 Layout const & defaultLayout = newDocClass->defaultLayout();
153                 Layout const & plainLayout = newDocClass->plainLayout();
154                 ParagraphList::iterator const end = insertion.end();
155                 ParagraphList::iterator par = insertion.begin();
156                 for (; par != end; ++par) {
157                         Layout const & parLayout = par->layout();
158                         if (parLayout == plainLayout)
159                                 par->setLayout(defaultLayout);
160                 }
161         }
162
163         InsetText in(buffer);
164         // Make sure there is no class difference.
165         in.paragraphs().clear();
166         // This works without copying any paragraph data because we have
167         // a specialized swap method for ParagraphList. This is important
168         // since we store pointers to insets at some places and we don't
169         // want to invalidate them.
170         insertion.swap(in.paragraphs());
171         cap::switchBetweenClasses(oldDocClass, newDocClass, in, errorlist);
172         insertion.swap(in.paragraphs());
173
174         ParagraphList::iterator tmpbuf = insertion.begin();
175         int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
176
177         depth_type max_depth = pars[pit].getMaxDepthAfter();
178
179         for (; tmpbuf != insertion.end(); ++tmpbuf) {
180                 // If we have a negative jump so that the depth would
181                 // go below 0 depth then we have to redo the delta to
182                 // this new max depth level so that subsequent
183                 // paragraphs are aligned correctly to this paragraph
184                 // at level 0.
185                 if (int(tmpbuf->params().depth()) + depth_delta < 0)
186                         depth_delta = 0;
187
188                 // Set the right depth so that we are not too deep or shallow.
189                 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
190                 if (tmpbuf->params().depth() > max_depth)
191                         tmpbuf->params().depth(max_depth);
192
193                 // Only set this from the 2nd on as the 2nd depends
194                 // for maxDepth still on pit.
195                 if (tmpbuf != insertion.begin())
196                         max_depth = tmpbuf->getMaxDepthAfter();
197
198                 // Set the inset owner of this paragraph.
199                 tmpbuf->setInsetOwner(target_inset);
200                 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
201                         // do not track deletion of invalid insets
202                         if (Inset * inset = tmpbuf->getInset(i))
203                                 if (!target_inset->insetAllowed(inset->lyxCode()))
204                                         tmpbuf->eraseChar(i--, false);
205                 }
206
207                 tmpbuf->setChange(Change(buffer.params().trackChanges ?
208                                          Change::INSERTED : Change::UNCHANGED));
209         }
210
211         bool const empty = pars[pit].empty();
212         if (!empty) {
213                 // Make the buf exactly the same layout as the cursor
214                 // paragraph.
215                 insertion.begin()->makeSameLayout(pars[pit]);
216         }
217
218         // Prepare the paragraphs and insets for insertion.
219         insertion.swap(in.paragraphs());
220
221         InsetIterator const i_end = inset_iterator_end(in);
222         for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
223         // Insets store buffer references so need updating.
224                 it->setBuffer(const_cast<Buffer &>(buffer));
225
226                 switch (it->lyxCode()) {
227  
228                 case LABEL_CODE: {
229                         // check for duplicates
230                         InsetCommand & lab = static_cast<InsetCommand &>(*it);
231                         docstring const oldname = lab.getParam("name");
232                         lab.updateCommand(oldname, false);
233                         docstring const newname = lab.getParam("name");
234                         if (oldname != newname) {
235                                 // adapt the references
236                                 for (InsetIterator itt = inset_iterator_begin(in); itt != i_end; ++itt) {
237                                         if (itt->lyxCode() == REF_CODE) {
238                                                 InsetCommand & ref = dynamic_cast<InsetCommand &>(*itt);
239                                                 if (ref.getParam("reference") == oldname)
240                                                         ref.setParam("reference", newname);
241                                         }
242                                 }
243                         }
244                         break;
245                 }
246
247                 case BIBITEM_CODE: {
248                         // check for duplicates
249                         InsetCommand & bib = static_cast<InsetCommand &>(*it);
250                         docstring const oldkey = bib.getParam("key");
251                         bib.updateCommand(oldkey, false);
252                         docstring const newkey = bib.getParam("key");
253                         if (oldkey != newkey) {
254                                 // adapt the references
255                                 for (InsetIterator itt = inset_iterator_begin(in); itt != i_end; ++itt) {
256                                         if (itt->lyxCode() == CITE_CODE) {
257                                                 InsetCommand & ref = dynamic_cast<InsetCommand &>(*itt);
258                                                 if (ref.getParam("key") == oldkey)
259                                                         ref.setParam("key", newkey);
260                                         }
261                                 }
262                         }
263                         break;
264                 }
265
266                 default:
267                         break; // nothing
268                 }
269         }
270         insertion.swap(in.paragraphs());
271
272         // Split the paragraph for inserting the buf if necessary.
273         if (!empty)
274                 breakParagraphConservative(buffer.params(), pars, pit, pos);
275
276         // Paste it!
277         if (empty) {
278                 pars.insert(boost::next(pars.begin(), pit),
279                             insertion.begin(),
280                             insertion.end());
281
282                 // merge the empty par with the last par of the insertion
283                 mergeParagraph(buffer.params(), pars,
284                                pit + insertion.size() - 1);
285         } else {
286                 pars.insert(boost::next(pars.begin(), pit + 1),
287                             insertion.begin(),
288                             insertion.end());
289
290                 // merge the first par of the insertion with the current par
291                 mergeParagraph(buffer.params(), pars, pit);
292         }
293         //FIXME: We should call setBuffer() on each inserted paragraph.
294         // instead, we call setBuffer() for the main inset at the beginning
295         // of updateLabels()
296
297         pit_type last_paste = pit + insertion.size() - 1;
298
299         // Store the new cursor position.
300         pit = last_paste;
301         pos = pars[last_paste].size();
302
303         // Join (conditionally) last pasted paragraph with next one, i.e.,
304         // the tail of the spliced document paragraph
305         if (!empty && last_paste + 1 != pit_type(pars.size())) {
306                 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
307                         mergeParagraph(buffer.params(), pars, last_paste);
308                 } else if (pars[last_paste + 1].empty()) {
309                         pars[last_paste + 1].makeSameLayout(pars[last_paste]);
310                         mergeParagraph(buffer.params(), pars, last_paste);
311                 } else if (pars[last_paste].empty()) {
312                         pars[last_paste].makeSameLayout(pars[last_paste + 1]);
313                         mergeParagraph(buffer.params(), pars, last_paste);
314                 } else {
315                         pars[last_paste + 1].stripLeadingSpaces(buffer.params().trackChanges);
316                         ++last_paste;
317                 }
318         }
319
320         return make_pair(PitPosPair(pit, pos), last_paste + 1);
321 }
322
323
324 PitPosPair eraseSelectionHelper(BufferParams const & params,
325         ParagraphList & pars,
326         pit_type startpit, pit_type endpit,
327         int startpos, int endpos)
328 {
329         // Start of selection is really invalid.
330         if (startpit == pit_type(pars.size()) ||
331             (startpos > pars[startpit].size()))
332                 return PitPosPair(endpit, endpos);
333
334         // Start and end is inside same paragraph
335         if (endpit == pit_type(pars.size()) || startpit == endpit) {
336                 endpos -= pars[startpit].eraseChars(startpos, endpos, params.trackChanges);
337                 return PitPosPair(endpit, endpos);
338         }
339
340         for (pit_type pit = startpit; pit != endpit + 1;) {
341                 pos_type const left  = (pit == startpit ? startpos : 0);
342                 pos_type right = (pit == endpit ? endpos : pars[pit].size() + 1);
343                 bool const merge = pars[pit].isMergedOnEndOfParDeletion(params.trackChanges);
344
345                 // Logically erase only, including the end-of-paragraph character
346                 pars[pit].eraseChars(left, right, params.trackChanges);
347
348                 // Separate handling of paragraph break:
349                 if (merge && pit != endpit &&
350                     (pit + 1 != endpit 
351                      || pars[pit].hasSameLayout(pars[endpit])
352                      || pars[endpit].size() == endpos)) {
353                         if (pit + 1 == endpit)
354                                 endpos += pars[pit].size();
355                         mergeParagraph(params, pars, pit);
356                         --endpit;
357                 } else
358                         ++pit;
359         }
360
361         // Ensure legal cursor pos:
362         endpit = startpit;
363         endpos = startpos;
364         return PitPosPair(endpit, endpos);
365 }
366
367
368 void putClipboard(ParagraphList const & paragraphs, 
369         DocumentClass const * const docclass, docstring const & plaintext)
370 {
371         // For some strange reason gcc 3.2 and 3.3 do not accept
372         // Buffer buffer(string(), false);
373         // This needs to be static to avoid a memory leak. When a Buffer is
374         // constructed, it constructs a BufferParams, which in turn constructs
375         // a DocumentClass, via new, that is never deleted. If we were to go to
376         // some kind of garbage collection there, or a shared_ptr, then this
377         // would not be needed.
378         static Buffer * buffer = theBufferList().newBuffer(
379                 FileName::tempName().absFilename() + "_clipboard.internal");
380         buffer->setUnnamed(true);
381         buffer->paragraphs() = paragraphs;
382         buffer->inset().setBuffer(*buffer);
383         buffer->params().setDocumentClass(docclass);
384         ostringstream lyx;
385         if (buffer->write(lyx))
386                 theClipboard().put(lyx.str(), plaintext);
387         else
388                 theClipboard().put(string(), plaintext);
389         // Save that memory
390         buffer->paragraphs().clear();
391 }
392
393
394 void copySelectionHelper(Buffer const & buf, ParagraphList const & pars,
395         pit_type startpit, pit_type endpit,
396         int start, int end, DocumentClass const * const dc, CutStack & cutstack)
397 {
398         LASSERT(0 <= start && start <= pars[startpit].size(), /**/);
399         LASSERT(0 <= end && end <= pars[endpit].size(), /**/);
400         LASSERT(startpit != endpit || start <= end, /**/);
401
402         // Clone the paragraphs within the selection.
403         ParagraphList copy_pars(boost::next(pars.begin(), startpit),
404                                 boost::next(pars.begin(), endpit + 1));
405
406         // Remove the end of the last paragraph; afterwards, remove the
407         // beginning of the first paragraph. Keep this order - there may only
408         // be one paragraph!  Do not track deletions here; this is an internal
409         // action not visible to the user
410
411         Paragraph & back = copy_pars.back();
412         back.eraseChars(end, back.size(), false);
413         Paragraph & front = copy_pars.front();
414         front.eraseChars(0, start, false);
415
416         ParagraphList::iterator it = copy_pars.begin();
417         ParagraphList::iterator it_end = copy_pars.end();
418
419         for (; it != it_end; it++) {
420                 // ERT paragraphs have the Language latex_language.
421                 // This is invalid outside of ERT, so we need to change it
422                 // to the buffer language.
423                 if (it->ownerCode() == ERT_CODE || it->ownerCode() == LISTINGS_CODE) {
424                         it->changeLanguage(buf.params(), latex_language, buf.language());
425                 }
426                 it->setInsetOwner(0);
427         }
428
429         // do not copy text (also nested in insets) which is marked as deleted
430         acceptChanges(copy_pars, buf.params());
431
432         DocumentClass * d = const_cast<DocumentClass *>(dc);
433         cutstack.push(make_pair(copy_pars, d));
434 }
435
436 } // namespace anon
437
438
439
440
441 namespace cap {
442
443 void region(CursorSlice const & i1, CursorSlice const & i2,
444             Inset::row_type & r1, Inset::row_type & r2,
445             Inset::col_type & c1, Inset::col_type & c2)
446 {
447         Inset & p = i1.inset();
448         c1 = p.col(i1.idx());
449         c2 = p.col(i2.idx());
450         if (c1 > c2)
451                 swap(c1, c2);
452         r1 = p.row(i1.idx());
453         r2 = p.row(i2.idx());
454         if (r1 > r2)
455                 swap(r1, r2);
456 }
457
458
459 docstring grabAndEraseSelection(Cursor & cur)
460 {
461         if (!cur.selection())
462                 return docstring();
463         docstring res = grabSelection(cur);
464         eraseSelection(cur);
465         return res;
466 }
467
468
469 bool reduceSelectionToOneCell(Cursor & cur)
470 {
471         if (!cur.selection() || !cur.inMathed())
472                 return false;
473
474         CursorSlice i1 = cur.selBegin();
475         CursorSlice i2 = cur.selEnd();
476         if (!i1.inset().asInsetMath())
477                 return false;
478
479         // the easy case: do nothing if only one cell is selected
480         if (i1.idx() == i2.idx())
481                 return true;
482         
483         cur.top().pos() = 0;
484         cur.resetAnchor();
485         cur.top().pos() = cur.top().lastpos();
486         
487         return true;
488 }
489
490
491 bool multipleCellsSelected(Cursor const & cur)
492 {
493         if (!cur.selection() || !cur.inMathed())
494                 return false;
495         
496         CursorSlice i1 = cur.selBegin();
497         CursorSlice i2 = cur.selEnd();
498         if (!i1.inset().asInsetMath())
499                 return false;
500         
501         if (i1.idx() == i2.idx())
502                 return false;
503         
504         return true;
505 }
506
507
508 void switchBetweenClasses(DocumentClass const * const oldone, 
509                 DocumentClass const * const newone, InsetText & in, ErrorList & errorlist)
510 {
511         errorlist.clear();
512
513         LASSERT(!in.paragraphs().empty(), /**/);
514         if (oldone == newone)
515                 return;
516         
517         DocumentClass const & oldtc = *oldone;
518         DocumentClass const & newtc = *newone;
519
520         // layouts
521         ParIterator end = par_iterator_end(in);
522         for (ParIterator it = par_iterator_begin(in); it != end; ++it) {
523                 docstring const name = it->layout().name();
524
525                 // the pasted text will keep their own layout name. If this layout does
526                 // not exist in the new document, it will behave like a standard layout.
527                 newtc.addLayoutIfNeeded(name);
528
529                 if (in.usePlainLayout())
530                         it->setLayout(newtc.plainLayout());
531                 else
532                         it->setLayout(newtc[name]);
533         }
534
535         // character styles
536         InsetIterator const i_end = inset_iterator_end(in);
537         for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
538                 InsetCollapsable * inset = it->asInsetCollapsable();
539                 if (!inset)
540                         continue;
541                 if (inset->lyxCode() != FLEX_CODE)
542                         // FIXME: Should we verify all InsetCollapsable?
543                         continue;
544                 inset->setLayout(newone);
545                 if (!inset->undefined())
546                         continue;
547                 // The flex inset is undefined in newtc
548                 docstring const s = bformat(_(
549                         "Flex inset %1$s is "
550                         "undefined because of class "
551                         "conversion from\n%2$s to %3$s"),
552                         inset->name(), from_utf8(oldtc.name()),
553                         from_utf8(newtc.name()));
554                 // To warn the user that something had to be done.
555                 errorlist.push_back(ErrorItem(
556                                 _("Undefined flex inset"),
557                                 s, it.paragraph().id(), it.pos(), it.pos() + 1));
558         }
559 }
560
561
562 vector<docstring> availableSelections(Buffer const * buf)
563 {
564         vector<docstring> selList;
565         if (!buf)
566                 return selList;
567
568         CutStack::const_iterator cit = theCuts.begin();
569         CutStack::const_iterator end = theCuts.end();
570         for (; cit != end; ++cit) {
571                 // we do not use cit-> here because gcc 2.9x does not
572                 // like it (JMarc)
573                 ParagraphList const & pars = (*cit).first;
574                 docstring asciiSel;
575                 ParagraphList::const_iterator pit = pars.begin();
576                 ParagraphList::const_iterator pend = pars.end();
577                 for (; pit != pend; ++pit) {
578                         Paragraph par(*pit, 0, 26);
579                         // adapt paragraph to current buffer.
580                         par.setBuffer(const_cast<Buffer &>(*buf));
581                         asciiSel += par.asString(AS_STR_INSETS);
582                         if (asciiSel.size() > 25) {
583                                 asciiSel.replace(22, docstring::npos,
584                                                  from_ascii("..."));
585                                 break;
586                         }
587                 }
588
589                 selList.push_back(asciiSel);
590         }
591
592         return selList;
593 }
594
595
596 size_type numberOfSelections()
597 {
598         return theCuts.size();
599 }
600
601
602 void cutSelection(Cursor & cur, bool doclear, bool realcut)
603 {
604         // This doesn't make sense, if there is no selection
605         if (!cur.selection())
606                 return;
607
608         // OK, we have a selection. This is always between cur.selBegin()
609         // and cur.selEnd()
610
611         if (cur.inTexted()) {
612                 Text * text = cur.text();
613                 LASSERT(text, /**/);
614
615                 saveSelection(cur);
616
617                 // make sure that the depth behind the selection are restored, too
618                 cur.recordUndoSelection();
619                 pit_type begpit = cur.selBegin().pit();
620                 pit_type endpit = cur.selEnd().pit();
621
622                 int endpos = cur.selEnd().pos();
623
624                 BufferParams const & bp = cur.buffer()->params();
625                 if (realcut) {
626                         copySelectionHelper(*cur.buffer(),
627                                 text->paragraphs(),
628                                 begpit, endpit,
629                                 cur.selBegin().pos(), endpos,
630                                 bp.documentClassPtr(), theCuts);
631                         // Stuff what we got on the clipboard.
632                         // Even if there is no selection.
633                         putClipboard(theCuts[0].first, theCuts[0].second,
634                                 cur.selectionAsString(true));
635                 }
636
637                 if (begpit != endpit)
638                         cur.updateFlags(Update::Force | Update::FitCursor);
639
640                 boost::tie(endpit, endpos) =
641                         eraseSelectionHelper(bp,
642                                 text->paragraphs(),
643                                 begpit, endpit,
644                                 cur.selBegin().pos(), endpos);
645
646                 // cutSelection can invalidate the cursor so we need to set
647                 // it anew. (Lgb)
648                 // we prefer the end for when tracking changes
649                 cur.pos() = endpos;
650                 cur.pit() = endpit;
651
652                 // sometimes necessary
653                 if (doclear
654                         && text->paragraphs()[begpit].stripLeadingSpaces(bp.trackChanges))
655                         cur.fixIfBroken();
656
657                 // need a valid cursor. (Lgb)
658                 cur.clearSelection();
659                 cur.buffer()->updateLabels();
660
661                 // tell tabular that a recent copy happened
662                 dirtyTabularStack(false);
663         }
664
665         if (cur.inMathed()) {
666                 if (cur.selBegin().idx() != cur.selEnd().idx()) {
667                         // The current selection spans more than one cell.
668                         // Record all cells
669                         cur.recordUndoInset();
670                 } else {
671                         // Record only the current cell to avoid a jumping
672                         // cursor after undo
673                         cur.recordUndo();
674                 }
675                 if (realcut)
676                         copySelection(cur);
677                 eraseSelection(cur);
678         }
679 }
680
681
682 void copySelection(Cursor const & cur)
683 {
684         copySelection(cur, cur.selectionAsString(true));
685 }
686
687
688 void copyInset(Cursor const & cur, Inset * inset, docstring const & plaintext)
689 {
690         ParagraphList pars;
691         Paragraph par;
692         BufferParams const & bp = cur.buffer()->params();
693         par.setLayout(bp.documentClass().plainLayout());
694         par.insertInset(0, inset, Change(Change::UNCHANGED));
695         pars.push_back(par);
696         theCuts.push(make_pair(pars, bp.documentClassPtr()));
697
698         // stuff the selection onto the X clipboard, from an explicit copy request
699         putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
700 }
701
702 namespace {
703
704 void copySelectionToStack(Cursor const & cur, CutStack & cutstack)
705 {
706         // this doesn't make sense, if there is no selection
707         if (!cur.selection())
708                 return;
709
710         // copySelection can not yet handle the case of cross idx selection
711         if (cur.selBegin().idx() != cur.selEnd().idx())
712                 return;
713
714         if (cur.inTexted()) {
715                 Text * text = cur.text();
716                 LASSERT(text, /**/);
717                 // ok we have a selection. This is always between cur.selBegin()
718                 // and sel_end cursor
719
720                 // copy behind a space if there is one
721                 ParagraphList & pars = text->paragraphs();
722                 pos_type pos = cur.selBegin().pos();
723                 pit_type par = cur.selBegin().pit();
724                 while (pos < pars[par].size() &&
725                        pars[par].isLineSeparator(pos) &&
726                        (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
727                         ++pos;
728
729                 copySelectionHelper(*cur.buffer(), pars, par, cur.selEnd().pit(),
730                         pos, cur.selEnd().pos(), 
731                         cur.buffer()->params().documentClassPtr(), cutstack);
732                 dirtyTabularStack(false);
733         }
734
735         if (cur.inMathed()) {
736                 //lyxerr << "copySelection in mathed" << endl;
737                 ParagraphList pars;
738                 Paragraph par;
739                 BufferParams const & bp = cur.buffer()->params();
740                 // FIXME This should be the plain layout...right?
741                 par.setLayout(bp.documentClass().plainLayout());
742                 par.insert(0, grabSelection(cur), Font(), Change(Change::UNCHANGED));
743                 pars.push_back(par);
744                 cutstack.push(make_pair(pars, bp.documentClassPtr()));
745         }
746 }
747
748 }
749
750
751 void copySelectionToStack()
752 {
753         if (!selectionBuffer.empty())
754                 theCuts.push(selectionBuffer[0]);
755 }
756
757
758 void copySelection(Cursor const & cur, docstring const & plaintext)
759 {
760         // In tablemode, because copy and paste actually use special table stack
761         // we do not attempt to get selected paragraphs under cursor. Instead, a
762         // paragraph with the plain text version is generated so that table cells
763         // can be pasted as pure text somewhere else.
764         if (cur.selBegin().idx() != cur.selEnd().idx()) {
765                 ParagraphList pars;
766                 Paragraph par;
767                 BufferParams const & bp = cur.buffer()->params();
768                 par.setLayout(bp.documentClass().plainLayout());
769                 par.insert(0, plaintext, Font(), Change(Change::UNCHANGED));
770                 pars.push_back(par);
771                 theCuts.push(make_pair(pars, bp.documentClassPtr()));
772         } else {
773                 copySelectionToStack(cur, theCuts);
774         }
775
776         // stuff the selection onto the X clipboard, from an explicit copy request
777         putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
778 }
779
780
781 void saveSelection(Cursor const & cur)
782 {
783         // This function is called, not when a selection is formed, but when
784         // a selection is cleared. Therefore, multiple keyboard selection
785         // will not repeatively trigger this function (bug 3877).
786         if (cur.selection() 
787             && cur.selBegin() == cur.bv().cursor().selBegin()
788             && cur.selEnd() == cur.bv().cursor().selEnd()) {
789                 LYXERR(Debug::SELECTION, "saveSelection: '" << cur.selectionAsString(true) << "'");
790                 copySelectionToStack(cur, selectionBuffer);
791         }
792 }
793
794
795 bool selection()
796 {
797         return !selectionBuffer.empty();
798 }
799
800
801 void clearSelection()
802 {
803         selectionBuffer.clear();
804 }
805
806
807 void clearCutStack()
808 {
809         theCuts.clear();
810 }
811
812
813 docstring selection(size_t sel_index)
814 {
815         return sel_index < theCuts.size()
816                 ? theCuts[sel_index].first.back().asString(AS_STR_INSETS | AS_STR_NEWLINES)
817                 : docstring();
818 }
819
820
821 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
822                         DocumentClass const * const docclass, ErrorList & errorList)
823 {
824         if (cur.inTexted()) {
825                 Text * text = cur.text();
826                 LASSERT(text, /**/);
827
828                 pit_type endpit;
829                 PitPosPair ppp;
830
831                 boost::tie(ppp, endpit) =
832                         pasteSelectionHelper(cur, parlist, docclass, errorList);
833                 cur.buffer()->updateLabels();
834                 cur.clearSelection();
835                 text->setCursor(cur, ppp.first, ppp.second);
836         }
837
838         // mathed is handled in InsetMathNest/InsetMathGrid
839         LASSERT(!cur.inMathed(), /**/);
840 }
841
842
843 void pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
844 {
845         // this does not make sense, if there is nothing to paste
846         if (!checkPastePossible(sel_index))
847                 return;
848
849         cur.recordUndo();
850         pasteParagraphList(cur, theCuts[sel_index].first,
851                            theCuts[sel_index].second, errorList);
852         cur.setSelection();
853 }
854
855
856 void pasteClipboardText(Cursor & cur, ErrorList & errorList, bool asParagraphs)
857 {
858         // Use internal clipboard if it is the most recent one
859         if (theClipboard().isInternal()) {
860                 pasteFromStack(cur, errorList, 0);
861                 return;
862         }
863
864         // First try LyX format
865         if (theClipboard().hasLyXContents()) {
866                 string lyx = theClipboard().getAsLyX();
867                 if (!lyx.empty()) {
868                         // For some strange reason gcc 3.2 and 3.3 do not accept
869                         // Buffer buffer(string(), false);
870                         Buffer buffer("", false);
871                         buffer.setUnnamed(true);
872                         if (buffer.readString(lyx)) {
873                                 cur.recordUndo();
874                                 pasteParagraphList(cur, buffer.paragraphs(),
875                                         buffer.params().documentClassPtr(), errorList);
876                                 cur.setSelection();
877                                 return;
878                         }
879                 }
880         }
881
882         // Then try plain text
883         docstring const text = theClipboard().getAsText();
884         if (text.empty())
885                 return;
886         cur.recordUndo();
887         if (asParagraphs)
888                 cur.text()->insertStringAsParagraphs(cur, text);
889         else
890                 cur.text()->insertStringAsLines(cur, text);
891 }
892
893
894 void pasteClipboardGraphics(Cursor & cur, ErrorList & /* errorList */,
895                             Clipboard::GraphicsType preferedType)
896 {
897         LASSERT(theClipboard().hasGraphicsContents(preferedType), /**/);
898
899         // get picture from clipboard
900         FileName filename = theClipboard().getAsGraphics(cur, preferedType);
901         if (filename.empty())
902                 return;
903
904         // create inset for graphic
905         InsetGraphics * inset = new InsetGraphics(*cur.buffer());
906         InsetGraphicsParams params;
907         params.filename = support::DocFileName(filename.absFilename());
908         inset->setParams(params);
909         cur.recordUndo();
910         cur.insert(inset);
911 }
912
913
914 void pasteSelection(Cursor & cur, ErrorList & errorList)
915 {
916         if (selectionBuffer.empty())
917                 return;
918         cur.recordUndo();
919         pasteParagraphList(cur, selectionBuffer[0].first,
920                            selectionBuffer[0].second, errorList);
921 }
922
923
924 void replaceSelectionWithString(Cursor & cur, docstring const & str, bool backwards)
925 {
926         cur.recordUndo();
927         DocIterator selbeg = cur.selectionBegin();
928
929         // Get font setting before we cut, we need a copy here, not a bare reference.
930         Font const font =
931                 selbeg.paragraph().getFontSettings(cur.buffer()->params(), selbeg.pos());
932
933         // Insert the new string
934         pos_type pos = cur.selEnd().pos();
935         Paragraph & par = cur.selEnd().paragraph();
936         docstring::const_iterator cit = str.begin();
937         docstring::const_iterator end = str.end();
938         for (; cit != end; ++cit, ++pos)
939                 par.insertChar(pos, *cit, font, cur.buffer()->params().trackChanges);
940
941         // Cut the selection
942         cutSelection(cur, true, false);
943
944         // select the replacement
945         if (backwards) {
946                 selbeg.pos() += str.length();
947                 cur.setSelection(selbeg, -int(str.length()));
948         } else
949                 cur.setSelection(selbeg, str.length());
950 }
951
952
953 void replaceSelection(Cursor & cur)
954 {
955         if (cur.selection())
956                 cutSelection(cur, true, false);
957 }
958
959
960 void eraseSelection(Cursor & cur)
961 {
962         //lyxerr << "cap::eraseSelection begin: " << cur << endl;
963         CursorSlice const & i1 = cur.selBegin();
964         CursorSlice const & i2 = cur.selEnd();
965         if (i1.inset().asInsetMath()) {
966                 saveSelection(cur);
967                 cur.top() = i1;
968                 if (i1.idx() == i2.idx()) {
969                         i1.cell().erase(i1.pos(), i2.pos());
970                         // We may have deleted i1.cell(cur.pos()).
971                         // Make sure that pos is valid.
972                         if (cur.pos() > cur.lastpos())
973                                 cur.pos() = cur.lastpos();
974                 } else {
975                         InsetMath * p = i1.asInsetMath();
976                         Inset::row_type r1, r2;
977                         Inset::col_type c1, c2;
978                         region(i1, i2, r1, r2, c1, c2);
979                         for (Inset::row_type row = r1; row <= r2; ++row)
980                                 for (Inset::col_type col = c1; col <= c2; ++col)
981                                         p->cell(p->index(row, col)).clear();
982                         // We've deleted the whole cell. Only pos 0 is valid.
983                         cur.pos() = 0;
984                 }
985                 // need a valid cursor. (Lgb)
986                 cur.clearSelection();
987         } else {
988                 lyxerr << "can't erase this selection 1" << endl;
989         }
990         //lyxerr << "cap::eraseSelection end: " << cur << endl;
991 }
992
993
994 void selDel(Cursor & cur)
995 {
996         //lyxerr << "cap::selDel" << endl;
997         if (cur.selection())
998                 eraseSelection(cur);
999 }
1000
1001
1002 void selClearOrDel(Cursor & cur)
1003 {
1004         //lyxerr << "cap::selClearOrDel" << endl;
1005         if (lyxrc.auto_region_delete)
1006                 selDel(cur);
1007         else
1008                 cur.setSelection(false);
1009 }
1010
1011
1012 docstring grabSelection(Cursor const & cur)
1013 {
1014         if (!cur.selection())
1015                 return docstring();
1016
1017 #if 0
1018         // grab selection by glueing multiple cells together. This is not what
1019         // we want because selections spanning multiple cells will get "&" and "\\"
1020         // seperators.
1021         ostringstream os;
1022         for (DocIterator dit = cur.selectionBegin();
1023              dit != cur.selectionEnd(); dit.forwardPos())
1024                 os << asString(dit.cell());
1025         return os.str();
1026 #endif
1027
1028         CursorSlice i1 = cur.selBegin();
1029         CursorSlice i2 = cur.selEnd();
1030
1031         if (i1.idx() == i2.idx()) {
1032                 if (i1.inset().asInsetMath()) {
1033                         MathData::const_iterator it = i1.cell().begin();
1034                         return asString(MathData(it + i1.pos(), it + i2.pos()));
1035                 } else {
1036                         return from_ascii("unknown selection 1");
1037                 }
1038         }
1039
1040         Inset::row_type r1, r2;
1041         Inset::col_type c1, c2;
1042         region(i1, i2, r1, r2, c1, c2);
1043
1044         docstring data;
1045         if (i1.inset().asInsetMath()) {
1046                 for (Inset::row_type row = r1; row <= r2; ++row) {
1047                         if (row > r1)
1048                                 data += "\\\\";
1049                         for (Inset::col_type col = c1; col <= c2; ++col) {
1050                                 if (col > c1)
1051                                         data += '&';
1052                                 data += asString(i1.asInsetMath()->
1053                                         cell(i1.asInsetMath()->index(row, col)));
1054                         }
1055                 }
1056         } else {
1057                 data = from_ascii("unknown selection 2");
1058         }
1059         return data;
1060 }
1061
1062
1063 void dirtyTabularStack(bool b)
1064 {
1065         dirty_tabular_stack_ = b;
1066 }
1067
1068
1069 bool tabularStackDirty()
1070 {
1071         return dirty_tabular_stack_;
1072 }
1073
1074
1075 } // namespace cap
1076 } // namespace lyx