]> git.lyx.org Git - lyx.git/blob - src/CutAndPaste.C
use the default converter for insetexternal, too
[lyx.git] / src / CutAndPaste.C
1 /*
2  * \file CutAndPaste.C
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  *
10  * Full author contact details are available in file CREDITS.
11  */
12
13 #include <config.h>
14
15 #include "CutAndPaste.h"
16
17 #include "buffer.h"
18 #include "buffer_funcs.h"
19 #include "bufferparams.h"
20 #include "BufferView.h"
21 #include "cursor.h"
22 #include "debug.h"
23 #include "errorlist.h"
24 #include "funcrequest.h"
25 #include "gettext.h"
26 #include "lfuns.h"
27 #include "lyxrc.h"
28 #include "lyxtext.h"
29 #include "lyxtextclasslist.h"
30 #include "paragraph.h"
31 #include "paragraph_funcs.h"
32 #include "ParagraphParameters.h"
33 #include "ParagraphList_fwd.h"
34 #include "pariterator.h"
35 #include "undo.h"
36
37 #include "insets/insettabular.h"
38
39 #include "mathed/math_data.h"
40 #include "mathed/math_inset.h"
41 #include "mathed/math_support.h"
42
43 #include "support/lstrings.h"
44
45 #include <boost/tuple/tuple.hpp>
46
47 using lyx::pos_type;
48 using lyx::pit_type;
49 using lyx::textclass_type;
50
51 using lyx::support::bformat;
52
53 using std::endl;
54 using std::for_each;
55 using std::make_pair;
56 using std::pair;
57 using std::vector;
58 using std::string;
59
60
61 namespace {
62
63 typedef std::pair<lyx::pit_type, int> PitPosPair;
64
65 typedef limited_stack<pair<ParagraphList, textclass_type> > CutStack;
66
67 CutStack theCuts(10);
68
69 struct resetOwnerAndChanges : public std::unary_function<Paragraph, void> {
70         void operator()(Paragraph & p) const {
71                 p.cleanChanges();
72                 p.setInsetOwner(0);
73         }
74 };
75
76
77 void region(CursorSlice const & i1, CursorSlice const & i2,
78         InsetBase::row_type & r1, InsetBase::row_type & r2,
79         InsetBase::col_type & c1, InsetBase::col_type & c2)
80 {
81         InsetBase & p = i1.inset();
82         c1 = p.col(i1.idx());
83         c2 = p.col(i2.idx());
84         if (c1 > c2)
85                 std::swap(c1, c2);
86         r1 = p.row(i1.idx());
87         r2 = p.row(i2.idx());
88         if (r1 > r2)
89                 std::swap(r1, r2);
90 }
91
92
93 bool checkPastePossible(int index)
94 {
95         return size_t(index) < theCuts.size() && !theCuts[index].first.empty();
96 }
97
98
99 pair<PitPosPair, pit_type>
100 pasteSelectionHelper(Buffer const & buffer, ParagraphList & pars,
101         pit_type pit, int pos,
102         textclass_type tc, size_t cut_index, ErrorList & errorlist)
103 {
104         if (!checkPastePossible(cut_index))
105                 return make_pair(PitPosPair(pit, pos), pit);
106
107         BOOST_ASSERT (pos <= pars[pit].size());
108
109         // Make a copy of the CaP paragraphs.
110         ParagraphList insertion = theCuts[cut_index].first;
111         textclass_type const textclass = theCuts[cut_index].second;
112
113         // Now remove all out of the pars which is NOT allowed in the
114         // new environment and set also another font if that is required.
115
116         // Make sure there is no class difference.
117         lyx::cap::SwitchLayoutsBetweenClasses(textclass, tc, insertion,
118                                     errorlist);
119
120         ParagraphList::iterator tmpbuf = insertion.begin();
121         int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
122
123         Paragraph::depth_type max_depth = pars[pit].getMaxDepthAfter();
124
125         for (; tmpbuf != insertion.end(); ++tmpbuf) {
126                 // If we have a negative jump so that the depth would
127                 // go below 0 depth then we have to redo the delta to
128                 // this new max depth level so that subsequent
129                 // paragraphs are aligned correctly to this paragraph
130                 // at level 0.
131                 if (int(tmpbuf->params().depth()) + depth_delta < 0)
132                         depth_delta = 0;
133
134                 // Set the right depth so that we are not too deep or shallow.
135                 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
136                 if (tmpbuf->params().depth() > max_depth)
137                         tmpbuf->params().depth(max_depth);
138
139                 // Only set this from the 2nd on as the 2nd depends
140                 // for maxDepth still on pit.
141                 if (tmpbuf != insertion.begin())
142                         max_depth = tmpbuf->getMaxDepthAfter();
143
144                 // Set the inset owner of this paragraph.
145                 tmpbuf->setInsetOwner(pars[pit].inInset());
146                 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
147                         if (tmpbuf->getChar(i) == Paragraph::META_INSET) {
148                                 if (!pars[pit].insetAllowed(tmpbuf->getInset(i)->lyxCode()))
149                                         tmpbuf->erase(i--);
150                         }
151                 }
152         }
153
154         bool const empty = pars[pit].empty();
155         if (!empty) {
156                 // Make the buf exactly the same layout as the cursor
157                 // paragraph.
158                 insertion.begin()->makeSameLayout(pars[pit]);
159         }
160
161         // Prepare the paragraphs and insets for insertion.
162         // A couple of insets store buffer references so need updating.
163         InsetText in;
164         std::swap(in.paragraphs(), insertion);
165
166         ParIterator fpit = par_iterator_begin(in);
167         ParIterator fend = par_iterator_end(in);
168
169         for (; fpit != fend; ++fpit) {
170                 InsetList::iterator lit = fpit->insetlist.begin();
171                 InsetList::iterator eit = fpit->insetlist.end();
172
173                 for (; lit != eit; ++lit) {
174                         switch (lit->inset->lyxCode()) {
175                         case InsetBase::TABULAR_CODE: {
176                                 InsetTabular * it = static_cast<InsetTabular*>(lit->inset);
177                                 it->buffer(&buffer);
178                                 break;
179                         }
180
181                         default:
182                                 break; // nothing
183                         }
184                 }
185         }
186         std::swap(in.paragraphs(), insertion);
187
188         // Split the paragraph for inserting the buf if necessary.
189         if (!empty)
190                 breakParagraphConservative(buffer.params(), pars, pit, pos);
191
192         // Paste it!
193         if (empty) {
194                 pars.insert(pars.begin() + pit, insertion.begin(),
195                             insertion.end());
196
197                 // merge the empty par with the last par of the insertion
198                 mergeParagraph(buffer.params(), pars,
199                                pit + insertion.size() - 1);
200         } else {
201                 pars.insert(pars.begin() + pit + 1, insertion.begin(),
202                             insertion.end());
203
204                 // merge the first par of the insertion with the current par
205                 mergeParagraph(buffer.params(), pars, pit);
206         }
207
208         pit_type last_paste = pit + insertion.size() - 1;
209
210         // Store the new cursor position.
211         pit = last_paste;
212         pos = pars[last_paste].size();
213
214         // Maybe some pasting.
215         if (!empty && last_paste + 1 != pit_type(pars.size())) {
216                 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
217                         mergeParagraph(buffer.params(), pars, last_paste);
218                 } else if (pars[last_paste + 1].empty()) {
219                         pars[last_paste + 1].makeSameLayout(pars[last_paste]);
220                         mergeParagraph(buffer.params(), pars, last_paste);
221                 } else if (pars[last_paste].empty()) {
222                         pars[last_paste].makeSameLayout(pars[last_paste + 1]);
223                         mergeParagraph(buffer.params(), pars, last_paste);
224                 } else {
225                         pars[last_paste + 1].stripLeadingSpaces();
226                         ++last_paste;
227                 }
228         }
229
230         return make_pair(PitPosPair(pit, pos), last_paste + 1);
231 }
232
233
234 PitPosPair eraseSelectionHelper(BufferParams const & params,
235         ParagraphList & pars,
236         pit_type startpit, pit_type endpit,
237         int startpos, int endpos, bool doclear)
238 {
239         if (startpit == pit_type(pars.size()) ||
240             (startpos > pars[startpit].size()))
241                 return PitPosPair(endpit, endpos);
242
243         if (endpit == pit_type(pars.size()) ||
244             startpit == endpit) {
245                 endpos -= pars[startpit].erase(startpos, endpos);
246                 return PitPosPair(endpit, endpos);
247         }
248
249         // clear end/begin fragments of the first/last par in selection
250         bool all_erased = true;
251
252         pars[startpit].erase(startpos, pars[startpit].size());
253         if (pars[startpit].size() != startpos)
254                 all_erased = false;
255
256         endpos -= pars[endpit].erase(0, endpos);
257         if (endpos != 0)
258                 all_erased = false;
259
260         // Loop through the deleted pars if any, erasing as needed
261         for (pit_type pit = startpit + 1; pit != endpit;) {
262                 // "erase" the contents of the par
263                 pars[pit].erase(0, pars[pit].size());
264                 if (!pars[pit].size()) {
265                         // remove the par if it's now empty
266                         pars.erase(pars.begin() + pit);
267                         --endpit;
268                 } else {
269                         ++pit;
270                         all_erased = false;
271                 }
272         }
273
274 #if 0 // FIXME: why for cut but not copy ?
275         // the cut selection should begin with standard layout
276         if (realcut) {
277                 buf->params().clear();
278                 buf->bibkey = 0;
279                 buf->layout(textclasslist[buffer->params.textclass].defaultLayoutName());
280         }
281 #endif
282
283         if (startpit + 1 == pit_type(pars.size()))
284                 return PitPosPair(endpit, endpos);
285
286         if (doclear) {
287                 pars[startpit + 1].stripLeadingSpaces();
288         }
289
290         // paste the paragraphs again, if possible
291         if (all_erased &&
292             (pars[startpit].hasSameLayout(pars[startpit + 1]) ||
293              pars[startpit + 1].empty())) {
294                 mergeParagraph(params, pars, startpit);
295                 // this because endpar gets deleted here!
296                 endpit = startpit;
297                 endpos = startpos;
298         }
299
300         return PitPosPair(endpit, endpos);
301
302 }
303
304
305 void copySelectionHelper(ParagraphList & pars,
306         pit_type startpit, pit_type endpit,
307         int start, int end, textclass_type tc)
308 {
309         BOOST_ASSERT(0 <= start && start <= pars[startpit].size());
310         BOOST_ASSERT(0 <= end && end <= pars[endpit].size());
311         BOOST_ASSERT(startpit != endpit || start <= end);
312
313         // Clone the paragraphs within the selection.
314         ParagraphList paragraphs(pars.begin() + startpit, pars.begin() + endpit + 1);
315         for_each(paragraphs.begin(), paragraphs.end(), resetOwnerAndChanges());
316
317         // Cut out the end of the last paragraph.
318         Paragraph & back = paragraphs.back();
319         back.erase(end, back.size());
320
321         // Cut out the begin of the first paragraph
322         Paragraph & front = paragraphs.front();
323         front.erase(0, start);
324
325         theCuts.push(make_pair(paragraphs, tc));
326 }
327
328
329
330 PitPosPair cutSelectionHelper(BufferParams const & params,
331         ParagraphList & pars, pit_type startpit, pit_type endpit,
332         int startpos, int endpos, textclass_type tc, bool doclear)
333 {
334         copySelectionHelper(pars, startpit, endpit, startpos, endpos, tc);
335         return eraseSelectionHelper(params, pars, startpit, endpit,
336                 startpos, endpos, doclear);
337 }
338
339
340 } // namespace anon
341
342
343
344
345 namespace lyx {
346 namespace cap {
347
348 string grabAndEraseSelection(LCursor & cur)
349 {
350         if (!cur.selection())
351                 return string();
352         string res = grabSelection(cur);
353         eraseSelection(cur);
354         cur.selection() = false;
355         return res;
356 }
357
358
359 int SwitchLayoutsBetweenClasses(textclass_type c1, textclass_type c2,
360         ParagraphList & pars, ErrorList & errorlist)
361 {
362         BOOST_ASSERT(!pars.empty());
363         int ret = 0;
364         if (c1 == c2)
365                 return ret;
366
367         LyXTextClass const & tclass1 = textclasslist[c1];
368         LyXTextClass const & tclass2 = textclasslist[c2];
369
370         InsetText in;
371         std::swap(in.paragraphs(), pars);
372
373         ParIterator end = par_iterator_end(in);
374         for (ParIterator it = par_iterator_begin(in); it != end; ++it) {
375                 string const name = it->layout()->name();
376                 bool hasLayout = tclass2.hasLayout(name);
377
378                 if (hasLayout)
379                         it->layout(tclass2[name]);
380                 else
381                         it->layout(tclass2.defaultLayout());
382
383                 if (!hasLayout && name != tclass1.defaultLayoutName()) {
384                         ++ret;
385                         string const s = bformat(
386                                 _("Layout had to be changed from\n%1$s to %2$s\n"
387                                 "because of class conversion from\n%3$s to %4$s"),
388                          name, it->layout()->name(), tclass1.name(), tclass2.name());
389                         // To warn the user that something had to be done.
390                         errorlist.push_back(ErrorItem("Changed Layout", s,
391                                                       it->id(), 0,
392                                                       it->size()));
393                 }
394         }
395         std::swap(in.paragraphs(), pars);
396         return ret;
397 }
398
399
400 std::vector<string> const availableSelections(Buffer const & buffer)
401 {
402         vector<string> selList;
403
404         CutStack::const_iterator cit = theCuts.begin();
405         CutStack::const_iterator end = theCuts.end();
406         for (; cit != end; ++cit) {
407                 // we do not use cit-> here because gcc 2.9x does not
408                 // like it (JMarc)
409                 ParagraphList const & pars = (*cit).first;
410                 string asciiSel;
411                 ParagraphList::const_iterator pit = pars.begin();
412                 ParagraphList::const_iterator pend = pars.end();
413                 for (; pit != pend; ++pit) {
414                         asciiSel += pit->asString(buffer, false);
415                         if (asciiSel.size() > 25) {
416                                 asciiSel.replace(22, string::npos, "...");
417                                 break;
418                         }
419                 }
420
421                 selList.push_back(asciiSel);
422         }
423
424         return selList;
425 }
426
427
428 int nrOfParagraphs()
429 {
430         return theCuts.empty() ? 0 : theCuts[0].first.size();
431 }
432
433
434 void cutSelection(LCursor & cur, bool doclear, bool realcut)
435 {
436         if (cur.inTexted()) {
437                 LyXText * text = cur.text();
438                 BOOST_ASSERT(text);
439                 // Stuff what we got on the clipboard. Even if there is no selection.
440
441                 // There is a problem with having the stuffing here in that the
442                 // larger the selection the slower LyX will get. This can be
443                 // solved by running the line below only when the selection has
444                 // finished. The solution used currently just works, to make it
445                 // faster we need to be more clever and probably also have more
446                 // calls to stuffClipboard. (Lgb)
447                 cur.bv().stuffClipboard(cur.selectionAsString(true));
448
449                 // This doesn't make sense, if there is no selection
450                 if (!cur.selection())
451                         return;
452
453                 // OK, we have a selection. This is always between cur.selBegin()
454                 // and cur.selEnd()
455
456                 // make sure that the depth behind the selection are restored, too
457                 recordUndoSelection(cur);
458                 pit_type begpit = cur.selBegin().pit();
459                 pit_type endpit = cur.selEnd().pit();
460
461                 int endpos = cur.selEnd().pos();
462
463                 BufferParams const & bp = cur.buffer().params();
464                 if (realcut) {
465                         copySelectionHelper(text->paragraphs(),
466                                 begpit, endpit,
467                                 cur.selBegin().pos(), endpos,
468                                 bp.textclass);
469                 }
470
471                 boost::tie(endpit, endpos) =
472                         eraseSelectionHelper(bp,
473                                 text->paragraphs(),
474                                 begpit, endpit,
475                                 cur.selBegin().pos(), endpos,
476                                 doclear);
477
478                 // sometimes necessary
479                 if (doclear)
480                         text->paragraphs()[begpit].stripLeadingSpaces();
481
482                 // cutSelection can invalidate the cursor so we need to set
483                 // it anew. (Lgb)
484                 // we prefer the end for when tracking changes
485                 cur.pos() = endpos;
486                 cur.pit() = endpit;
487
488                 // need a valid cursor. (Lgb)
489                 cur.clearSelection();
490                 text->updateCounters();
491         }
492
493         if (cur.inMathed()) {
494                 lyxerr << "cutSelection in mathed" << endl;
495                 LCursor tmp = cur;
496                 copySelection(cur);
497                 cur.selection() = false;
498                 eraseSelection(tmp);
499         }
500 }
501
502
503 void copySelection(LCursor & cur)
504 {
505         // stuff the selection onto the X clipboard, from an explicit copy request
506         cur.bv().stuffClipboard(cur.selectionAsString(true));
507
508         // this doesn't make sense, if there is no selection
509         if (!cur.selection())
510                 return;
511
512         if (cur.inTexted()) {
513                 LyXText * text = cur.text();
514                 BOOST_ASSERT(text);
515                 // ok we have a selection. This is always between cur.selBegin()
516                 // and sel_end cursor
517
518                 // copy behind a space if there is one
519                 ParagraphList & pars = text->paragraphs();
520                 pos_type pos = cur.selBegin().pos();
521                 pit_type par = cur.selBegin().pit();
522                 while (pos < pars[par].size()
523                                          && pars[par].isLineSeparator(pos)
524                                          && (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
525                         ++pos;
526
527                 copySelectionHelper(pars, par, cur.selEnd().pit(),
528                         pos, cur.selEnd().pos(), cur.buffer().params().textclass);
529         }
530
531         if (cur.inMathed()) {
532                 lyxerr << "copySelection in mathed" << endl;
533                 ParagraphList pars;
534                 pars.push_back(Paragraph());
535                 BufferParams const & bp = cur.buffer().params();
536                 pars.back().layout(bp.getLyXTextClass().defaultLayout());
537                 for_each(pars.begin(), pars.end(), resetOwnerAndChanges());
538                 pars.back().insert(0, grabSelection(cur), LyXFont());
539                 theCuts.push(make_pair(pars, bp.textclass));
540         }
541 }
542
543
544 std::string getSelection(Buffer const & buf, size_t sel_index)
545 {
546         return sel_index < theCuts.size()
547                 ? theCuts[sel_index].first.back().asString(buf, false)
548                 : string();
549 }
550
551
552 void pasteSelection(LCursor & cur, size_t sel_index)
553 {
554         // this does not make sense, if there is nothing to paste
555         lyxerr << "#### pasteSelection " << sel_index << endl;
556         if (!checkPastePossible(sel_index))
557                 return;
558
559         if (cur.inTexted()) {
560                 LyXText * text = cur.text();
561                 BOOST_ASSERT(text);
562
563                 recordUndo(cur);
564
565                 pit_type endpit;
566                 PitPosPair ppp;
567
568                 ErrorList el;
569
570                 boost::tie(ppp, endpit) =
571                         pasteSelectionHelper(cur.buffer(),
572                                                                 text->paragraphs(),
573                                                                 cur.pit(), cur.pos(),
574                                                                 cur.buffer().params().textclass,
575                                                                 sel_index, el);
576                 bufferErrors(cur.buffer(), el);
577                 cur.bv().showErrorList(_("Paste"));
578
579                 cur.clearSelection();
580                 cur.resetAnchor();
581                 text->setCursor(cur, ppp.first, ppp.second);
582                 cur.setSelection();
583                 text->updateCounters();
584         }
585
586         if (cur.inMathed()) {
587                 lyxerr << "### should be handled in MathNest/GridInset" << endl;
588         }
589 }
590
591
592 void setSelectionRange(LCursor & cur, pos_type length)
593 {
594         LyXText * text = cur.text();
595         BOOST_ASSERT(text);
596         if (!length)
597                 return;
598         cur.resetAnchor();
599         while (length--)
600                 text->cursorRight(cur);
601         cur.setSelection();
602 }
603
604
605 // simple replacing. The font of the first selected character is used
606 void replaceSelectionWithString(LCursor & cur, string const & str)
607 {
608         LyXText * text = cur.text();
609         BOOST_ASSERT(text);
610         recordUndo(cur);
611
612         // Get font setting before we cut
613         pos_type pos = cur.selEnd().pos();
614         Paragraph & par = text->getPar(cur.selEnd().pit());
615         LyXFont const font =
616                 par.getFontSettings(cur.buffer().params(), cur.selBegin().pos());
617
618         // Insert the new string
619         string::const_iterator cit = str.begin();
620         string::const_iterator end = str.end();
621         for (; cit != end; ++cit, ++pos)
622                 par.insertChar(pos, (*cit), font);
623
624         // Cut the selection
625         cutSelection(cur, true, false);
626 }
627
628
629 void replaceSelection(LCursor & cur)
630 {
631         if (cur.selection())
632                 cutSelection(cur, true, false);
633 }
634
635
636 // only used by the spellchecker
637 void replaceWord(LCursor & cur, string const & replacestring)
638 {
639         LyXText * text = cur.text();
640         BOOST_ASSERT(text);
641
642         replaceSelectionWithString(cur, replacestring);
643         setSelectionRange(cur, replacestring.length());
644
645         // Go back so that replacement string is also spellchecked
646         for (string::size_type i = 0; i < replacestring.length() + 1; ++i)
647                 text->cursorLeft(cur);
648 }
649
650
651 void eraseSelection(LCursor & cur)
652 {
653         //lyxerr << "LCursor::eraseSelection begin: " << cur << endl;
654         CursorSlice const & i1 = cur.selBegin();
655         CursorSlice const & i2 = cur.selEnd();
656         if (i1.inset().asMathInset()) {
657                 if (i1.idx() == i2.idx()) {
658                         i1.cell().erase(i1.pos(), i2.pos());
659                 } else {
660                         MathInset * p = i1.asMathInset();
661                         InsetBase::row_type r1, r2;
662                         InsetBase::col_type c1, c2;
663                         region(i1, i2, r1, r2, c1, c2);
664                         for (InsetBase::row_type row = r1; row <= r2; ++row)
665                                 for (InsetBase::col_type col = c1; col <= c2; ++col)
666                                         p->cell(p->index(row, col)).clear();
667                 }
668                 cur.back() = i1;
669                 cur.pos() = 0; // We've deleted the whole cell. Only pos 0 is valid.
670                 cur.resetAnchor();
671         } else {
672                 lyxerr << "can't erase this selection 1" << endl;
673         }
674         //lyxerr << "LCursor::eraseSelection end: " << cur << endl;
675 }
676
677
678 void selDel(LCursor & cur)
679 {
680         //lyxerr << "LCursor::selDel" << endl;
681         if (cur.selection()) {
682                 eraseSelection(cur);
683                 cur.selection() = false;
684         }
685 }
686
687
688 void selClearOrDel(LCursor & cur)
689 {
690         //lyxerr << "LCursor::selClearOrDel" << endl;
691         if (lyxrc.auto_region_delete)
692                 selDel(cur);
693         else
694                 cur.selection() = false;
695 }
696
697
698 string grabSelection(LCursor & cur)
699 {
700         if (!cur.selection())
701                 return string();
702
703         CursorSlice i1 = cur.selBegin();
704         CursorSlice i2 = cur.selEnd();
705
706         if (i1.idx() == i2.idx()) {
707                 if (i1.inset().asMathInset()) {
708                         MathArray::const_iterator it = i1.cell().begin();
709                         return asString(MathArray(it + i1.pos(), it + i2.pos()));
710                 } else {
711                         return "unknown selection 1";
712                 }
713         }
714
715         InsetBase::row_type r1, r2;
716         InsetBase::col_type c1, c2;
717         region(i1, i2, r1, r2, c1, c2);
718
719         string data;
720         if (i1.inset().asMathInset()) {
721                 for (InsetBase::row_type row = r1; row <= r2; ++row) {
722                         if (row > r1)
723                                 data += "\\\\";
724                         for (InsetBase::col_type col = c1; col <= c2; ++col) {
725                                 if (col > c1)
726                                         data += '&';
727                                 data += asString(i1.asMathInset()->
728                                         cell(i1.asMathInset()->index(row, col)));
729                         }
730                 }
731         } else {
732                 data = "unknown selection 2";
733         }
734         return data;
735 }
736
737
738 } // namespace cap
739 } // namespace lyx