]> git.lyx.org Git - lyx.git/blob - src/Text3.cpp
be9a189029a679b6d41991561737133746c38a1a
[lyx.git] / src / Text3.cpp
1 /**
2  * \file Text3.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Asger Alstrup
7  * \author Lars Gullik Bjønnes
8  * \author Alfredo Braunstein
9  * \author Angus Leeming
10  * \author John Levon
11  * \author André Pönitz
12  *
13  * Full author contact details are available in file CREDITS.
14  */
15
16 #include <config.h>
17
18 #include "Text.h"
19
20 #include "Bidi.h"
21 #include "BranchList.h"
22 #include "FloatList.h"
23 #include "FuncStatus.h"
24 #include "Buffer.h"
25 #include "buffer_funcs.h"
26 #include "BufferParams.h"
27 #include "BufferView.h"
28 #include "Changes.h"
29 #include "Cursor.h"
30 #include "CutAndPaste.h"
31 #include "DispatchResult.h"
32 #include "ErrorList.h"
33 #include "factory.h"
34 #include "FuncRequest.h"
35 #include "InsetList.h"
36 #include "Intl.h"
37 #include "Language.h"
38 #include "Layout.h"
39 #include "LyXAction.h"
40 #include "LyXFunc.h"
41 #include "Lexer.h"
42 #include "LyXRC.h"
43 #include "Paragraph.h"
44 #include "ParagraphParameters.h"
45 #include "TextClass.h"
46 #include "TextMetrics.h"
47 #include "VSpace.h"
48
49 #include "frontends/Application.h"
50 #include "frontends/Clipboard.h"
51 #include "frontends/LyXView.h"
52 #include "frontends/Selection.h"
53 #include "frontends/WorkArea.h"
54
55 #include "insets/InsetCollapsable.h"
56 #include "insets/InsetCommand.h"
57 #include "insets/InsetExternal.h"
58 #include "insets/InsetFloat.h"
59 #include "insets/InsetFloatList.h"
60 #include "insets/InsetGraphics.h"
61 #include "insets/InsetGraphicsParams.h"
62 #include "insets/InsetNewline.h"
63 #include "insets/InsetQuotes.h"
64 #include "insets/InsetSpecialChar.h"
65 #include "insets/InsetText.h"
66 #include "insets/InsetWrap.h"
67
68 #include "support/convert.h"
69 #include "support/debug.h"
70 #include "support/gettext.h"
71 #include "support/lstrings.h"
72 #include "support/lyxtime.h"
73 #include "support/os.h"
74
75 #include "mathed/InsetMathHull.h"
76 #include "mathed/MathMacroTemplate.h"
77
78 #include <boost/next_prior.hpp>
79
80 #include <clocale>
81 #include <sstream>
82
83 using namespace std;
84 using namespace lyx::support;
85
86 namespace lyx {
87
88 using cap::copySelection;
89 using cap::cutSelection;
90 using cap::pasteFromStack;
91 using cap::pasteClipboardText;
92 using cap::pasteClipboardGraphics;
93 using cap::replaceSelection;
94 using cap::grabAndEraseSelection;
95 using cap::selClearOrDel;
96
97 // globals...
98 static Font freefont(ignore_font, ignore_language);
99 static bool toggleall = false;
100
101 static void toggleAndShow(Cursor & cur, Text * text,
102         Font const & font, bool toggleall = true)
103 {
104         text->toggleFree(cur, font, toggleall);
105
106         if (font.language() != ignore_language ||
107             font.fontInfo().number() != FONT_IGNORE) {
108                 TextMetrics const & tm = cur.bv().textMetrics(text);
109                 if (cur.boundary() != tm.isRTLBoundary(cur.pit(), cur.pos(),
110                                                        cur.real_current_font))
111                         text->setCursor(cur, cur.pit(), cur.pos(),
112                                         false, !cur.boundary());
113         }
114 }
115
116
117 static void moveCursor(Cursor & cur, bool selecting)
118 {
119         if (selecting || cur.mark())
120                 cur.setSelection();
121 }
122
123
124 static void finishChange(Cursor & cur, bool selecting)
125 {
126         cur.finishUndo();
127         moveCursor(cur, selecting);
128 }
129
130
131 static void mathDispatch(Cursor & cur, FuncRequest const & cmd, bool display)
132 {
133         cur.recordUndo();
134         docstring sel = cur.selectionAsString(false);
135
136         // It may happen that sel is empty but there is a selection
137         replaceSelection(cur);
138
139         // Is this a valid formula?
140         bool valid = true;
141
142         if (sel.empty()) {
143 #ifdef ENABLE_ASSERTIONS
144                 const int old_pos = cur.pos();
145 #endif
146                 cur.insert(new InsetMathHull(hullSimple));
147 #ifdef ENABLE_ASSERTIONS
148                 LASSERT(old_pos == cur.pos(), /**/);
149 #endif
150                 cur.nextInset()->edit(cur, true);
151                 // don't do that also for LFUN_MATH_MODE
152                 // unless you want end up with always changing
153                 // to mathrm when opening an inlined inset --
154                 // I really hate "LyXfunc overloading"...
155                 if (display)
156                         cur.dispatch(FuncRequest(LFUN_MATH_DISPLAY));
157                 // Avoid an unnecessary undo step if cmd.argument
158                 // is empty
159                 if (!cmd.argument().empty())
160                         cur.dispatch(FuncRequest(LFUN_MATH_INSERT,
161                                                  cmd.argument()));
162         } else {
163                 // create a macro if we see "\\newcommand"
164                 // somewhere, and an ordinary formula
165                 // otherwise
166                 if (sel.find(from_ascii("\\newcommand")) == string::npos
167                                 && sel.find(from_ascii("\\newlyxcommand")) == string::npos
168                                 && sel.find(from_ascii("\\def")) == string::npos)
169                 {
170                         InsetMathHull * formula = new InsetMathHull;
171                         string const selstr = to_utf8(sel);
172                         istringstream is(selstr);
173                         Lexer lex;
174                         lex.setStream(is);
175                         if (!formula->readQuiet(lex)) {
176                                 // No valid formula, let's try with delims
177                                 is.str("$" + selstr + "$");
178                                 lex.setStream(is);
179                                 if (!formula->readQuiet(lex)) {
180                                         // Still not valid, leave it as is
181                                         valid = false;
182                                         delete formula;
183                                         cur.insert(sel);
184                                 } else
185                                         cur.insert(formula);
186                         } else
187                                 cur.insert(formula);
188                 } else {
189                         cur.insert(new MathMacroTemplate(sel));
190                 }
191         }
192         if (valid)
193                 cur.message(from_utf8(N_("Math editor mode")));
194         else
195                 cur.message(from_utf8(N_("No valid math formula")));
196 }
197
198
199 void regexpDispatch(Cursor & cur, FuncRequest const & cmd)
200 {
201         BOOST_ASSERT(cmd.action == LFUN_REGEXP_MODE);
202         if (cur.inRegexped()) {
203                 cur.message(_("Already in regexp mode"));
204                 return;
205         }
206         cur.recordUndo();
207         docstring sel = cur.selectionAsString(false);
208
209         // It may happen that sel is empty but there is a selection
210         replaceSelection(cur);
211
212         cur.insert(new InsetMathHull(hullRegexp));
213         cur.nextInset()->edit(cur, true);
214         cur.niceInsert(sel);
215
216         cur.message(_("Regexp editor mode"));
217 }
218
219
220 static void specialChar(Cursor & cur, InsetSpecialChar::Kind kind)
221 {
222         cur.recordUndo();
223         cap::replaceSelection(cur);
224         cur.insert(new InsetSpecialChar(kind));
225         cur.posForward();
226 }
227
228
229 static bool doInsertInset(Cursor & cur, Text * text,
230         FuncRequest const & cmd, bool edit, bool pastesel)
231 {
232         Buffer & buffer = cur.bv().buffer();
233         BufferParams const & bparams = buffer.params();
234         Inset * inset = createInset(buffer, cmd);
235         if (!inset)
236                 return false;
237
238         if (InsetCollapsable * ci = inset->asInsetCollapsable())
239                 ci->setButtonLabel();
240
241         cur.recordUndo();
242         if (cmd.action == LFUN_INDEX_INSERT) {
243                 docstring ds = subst(text->getStringToIndex(cur), '\n', ' ');
244                 text->insertInset(cur, inset);
245                 if (edit)
246                         inset->edit(cur, true);
247                 // Now put this into inset
248                 cur.text()->insertStringAsLines(cur, ds, cur.current_font);
249                 cur.leaveInset(*inset);
250                 return true;
251         }
252
253         bool gotsel = false;
254         if (cur.selection()) {
255                 cutSelection(cur, false, pastesel);
256                 cur.clearSelection();
257                 gotsel = true;
258         }
259         text->insertInset(cur, inset);
260
261         if (edit)
262                 inset->edit(cur, true);
263
264         if (!gotsel || !pastesel)
265                 return true;
266
267         pasteFromStack(cur, cur.buffer()->errorList("Paste"), 0);
268         cur.buffer()->errors("Paste");
269         cur.clearSelection(); // bug 393
270         cur.finishUndo();
271         InsetText * insetText = dynamic_cast<InsetText *>(inset);
272         if (insetText && (!insetText->allowMultiPar() || cur.lastpit() == 0)) {
273                 // reset first par to default
274                 cur.text()->paragraphs().begin()
275                         ->setPlainOrDefaultLayout(bparams.documentClass());
276                 cur.pos() = 0;
277                 cur.pit() = 0;
278                 // Merge multiple paragraphs -- hack
279                 while (cur.lastpit() > 0)
280                         mergeParagraph(bparams, cur.text()->paragraphs(), 0);
281                 cur.leaveInset(*inset);
282         } else {
283                 cur.leaveInset(*inset);
284                 // reset surrounding par to default
285                 DocumentClass const & dc = bparams.documentClass();
286                 docstring const layoutname = inset->usePlainLayout()
287                         ? dc.plainLayoutName()
288                         : dc.defaultLayoutName();
289                 text->setLayout(cur, layoutname);
290         }
291
292         return true;
293 }
294
295
296 string const freefont2string()
297 {
298         return freefont.toString(toggleall);
299 }
300
301
302 static void dragMove(Cursor & cur, int moveid, int movetoid)
303 {
304         // Create pointers to buffers
305         Buffer & buf_move = *cur.buffer();
306         DocIterator dit_move = buf_move.getParFromID(moveid);
307         DocIterator dit_dest = buf_move.getParFromID(movetoid);
308
309         pit_type & pit_move = dit_move.pit();
310         pit_type & pit_dest = dit_dest.pit();
311         ParagraphList & pars = dit_move.text()->paragraphs();
312
313         // Create references to the paragraphs to be moved
314         ParagraphList::iterator const bgn = pars.begin();
315         ParagraphList::iterator dest_start = boost::next(bgn, pit_dest);
316
317         // The first paragraph of the area to be copied:
318         ParagraphList::iterator start = boost::next(bgn, pit_move);
319         // The final paragraph of area to be copied:
320         ParagraphList::iterator finish = start;
321         ParagraphList::iterator const end = pars.end();
322
323         // Move out (down) from this section header
324         if (finish != end)
325                 ++finish;
326
327         // Seek the one (on same level) below
328         int const thistoclevel = start->layout().toclevel;
329         for (; finish != end; ++finish) {
330                 int const toclevel = finish->layout().toclevel;
331                 if (toclevel != Layout::NOT_IN_TOC
332                     && toclevel <= thistoclevel)
333                         break;
334         }
335
336         if (start == pars.begin() || start == dest_start)
337                 // Nothing to move
338                 return;
339
340         pars.insert(dest_start, start, finish);
341         pars.erase(start, finish);
342
343         // FIXME: This only really needs doing for the newly
344         // introduced paragraphs. Something like:
345         //      pit_type const numpars = distance(start, finish);
346         //      start = boost::next(bgn, pit);
347         //      finish = boost::next(start, numpars);
348         //      for (; start != finish; ++start)
349         //              start->setBuffer(buf);
350         // But while this seems to work, it is kind of fragile.
351         buf_move.inset().setBuffer(buf_move);
352 }
353
354
355 /// the type of outline operation
356 enum OutlineOp {
357         OutlineUp, // Move this header with text down
358         OutlineDown,   // Move this header with text up
359         OutlineIn, // Make this header deeper
360         OutlineOut // Make this header shallower
361 };
362
363
364 static void outline(OutlineOp mode, Cursor & cur)
365 {
366         Buffer & buf = *cur.buffer();
367         pit_type & pit = cur.pit();
368         ParagraphList & pars = buf.text().paragraphs();
369         ParagraphList::iterator const bgn = pars.begin();
370         // The first paragraph of the area to be copied:
371         ParagraphList::iterator start = boost::next(bgn, pit);
372         // The final paragraph of area to be copied:
373         ParagraphList::iterator finish = start;
374         ParagraphList::iterator const end = pars.end();
375
376         DocumentClass const & tc = buf.params().documentClass();
377
378         int const thistoclevel = start->layout().toclevel;
379         int toclevel;
380
381         // Move out (down) from this section header
382         if (finish != end)
383                 ++finish;
384
385         // Seek the one (on same level) below
386         for (; finish != end; ++finish) {
387                 toclevel = finish->layout().toclevel;
388                 if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel)
389                         break;
390         }
391
392         switch (mode) {
393                 case OutlineUp: {
394                         if (start == pars.begin())
395                                 // Nothing to move.
396                                 return;
397                         ParagraphList::iterator dest = start;
398                         // Move out (up) from this header
399                         if (dest == bgn)
400                                 return;
401                         // Search previous same-level header above
402                         do {
403                                 --dest;
404                                 toclevel = dest->layout().toclevel;
405                         } while(dest != bgn
406                                 && (toclevel == Layout::NOT_IN_TOC
407                                     || toclevel > thistoclevel));
408                         // Not found; do nothing
409                         if (toclevel == Layout::NOT_IN_TOC || toclevel > thistoclevel)
410                                 return;
411                         pit_type const newpit = distance(bgn, dest);
412                         pit_type const len = distance(start, finish);
413                         pit_type const deletepit = pit + len;
414                         buf.undo().recordUndo(cur, ATOMIC_UNDO, newpit, deletepit - 1);
415                         pars.splice(dest, start, finish);
416                         cur.pit() = newpit;
417                         break;
418                 }
419                 case OutlineDown: {
420                         if (finish == end)
421                                 // Nothing to move.
422                                 return;
423                         // Go one down from *this* header:
424                         ParagraphList::iterator dest = boost::next(finish, 1);
425                         // Go further down to find header to insert in front of:
426                         for (; dest != end; ++dest) {
427                                 toclevel = dest->layout().toclevel;
428                                 if (toclevel != Layout::NOT_IN_TOC
429                                       && toclevel <= thistoclevel)
430                                         break;
431                         }
432                         // One such was found:
433                         pit_type newpit = distance(bgn, dest);
434                         buf.undo().recordUndo(cur, ATOMIC_UNDO, pit, newpit - 1);
435                         pit_type const len = distance(start, finish);
436                         pars.splice(dest, start, finish);
437                         cur.pit() = newpit - len;
438                         break;
439                 }
440                 case OutlineIn: {
441                         pit_type const len = distance(start, finish);
442                         buf.undo().recordUndo(cur, ATOMIC_UNDO, pit, pit + len - 1);
443                         for (; start != finish; ++start) {
444                                 toclevel = start->layout().toclevel;
445                                 if (toclevel == Layout::NOT_IN_TOC)
446                                         continue;
447                                 DocumentClass::const_iterator lit = tc.begin();
448                                 DocumentClass::const_iterator len = tc.end();
449                                 for (; lit != len; ++lit) {
450                                         if (lit->toclevel == toclevel + 1 &&
451                                             start->layout().labeltype == lit->labeltype) {
452                                                 start->setLayout(*lit);
453                                                 break;
454                                         }
455                                 }
456                         }
457                         break;
458                 }
459                 case OutlineOut: {
460                         pit_type const len = distance(start, finish);
461                         buf.undo().recordUndo(cur, ATOMIC_UNDO, pit, pit + len - 1);
462                         for (; start != finish; ++start) {
463                                 toclevel = start->layout().toclevel;
464                                 if (toclevel == Layout::NOT_IN_TOC)
465                                         continue;
466                                 DocumentClass::const_iterator lit = tc.begin();
467                                 DocumentClass::const_iterator len = tc.end();
468                                 for (; lit != len; ++lit) {
469                                         if (lit->toclevel == toclevel - 1 &&
470                                                 start->layout().labeltype == lit->labeltype) {
471                                                         start->setLayout(*lit);
472                                                         break;
473                                         }
474                                 }
475                         }
476                         break;
477                 }
478         }
479 }
480
481
482 void Text::number(Cursor & cur)
483 {
484         FontInfo font = ignore_font;
485         font.setNumber(FONT_TOGGLE);
486         toggleAndShow(cur, this, Font(font, ignore_language));
487 }
488
489
490 bool Text::isRTL(Paragraph const & par) const
491 {
492         Buffer const & buffer = owner_->buffer();
493         return par.isRTL(buffer.params());
494 }
495
496
497 void Text::dispatch(Cursor & cur, FuncRequest & cmd)
498 {
499         LYXERR(Debug::ACTION, "Text::dispatch: cmd: " << cmd);
500
501         // Dispatch if the cursor is inside the text. It is not the
502         // case for context menus (bug 5797).
503         if (cur.text() != this) {
504                 cur.undispatched();
505                 return;
506         }
507
508         BufferView * bv = &cur.bv();
509         TextMetrics * tm = &bv->textMetrics(this);
510         if (!tm->contains(cur.pit())) {
511                 lyx::dispatch(FuncRequest(LFUN_SCREEN_SHOW_CURSOR));
512                 tm = &bv->textMetrics(this);
513         }
514
515         // FIXME: We use the update flag to indicates wether a singlePar or a
516         // full screen update is needed. We reset it here but shall we restore it
517         // at the end?
518         cur.noUpdate();
519
520         LASSERT(cur.text() == this, /**/);
521         CursorSlice oldTopSlice = cur.top();
522         bool oldBoundary = cur.boundary();
523         bool sel = cur.selection();
524         // Signals that, even if needsUpdate == false, an update of the
525         // cursor paragraph is required
526         bool singleParUpdate = lyxaction.funcHasFlag(cmd.action,
527                 LyXAction::SingleParUpdate);
528         // Signals that a full-screen update is required
529         bool needsUpdate = !(lyxaction.funcHasFlag(cmd.action,
530                 LyXAction::NoUpdate) || singleParUpdate);
531
532         switch (cmd.action) {
533
534         case LFUN_PARAGRAPH_MOVE_DOWN: {
535                 pit_type const pit = cur.pit();
536                 recUndo(cur, pit, pit + 1);
537                 cur.finishUndo();
538                 pars_.swap(pit, pit + 1);
539                 cur.buffer()->updateLabels();
540                 needsUpdate = true;
541                 ++cur.pit();
542                 break;
543         }
544
545         case LFUN_PARAGRAPH_MOVE_UP: {
546                 pit_type const pit = cur.pit();
547                 recUndo(cur, pit - 1, pit);
548                 cur.finishUndo();
549                 pars_.swap(pit, pit - 1);
550                 cur.buffer()->updateLabels();
551                 --cur.pit();
552                 needsUpdate = true;
553                 break;
554         }
555
556         case LFUN_APPENDIX: {
557                 Paragraph & par = cur.paragraph();
558                 bool start = !par.params().startOfAppendix();
559
560 // FIXME: The code below only makes sense at top level.
561 // Should LFUN_APPENDIX be restricted to top-level paragraphs?
562                 // ensure that we have only one start_of_appendix in this document
563                 // FIXME: this don't work for multipart document!
564                 for (pit_type tmp = 0, end = pars_.size(); tmp != end; ++tmp) {
565                         if (pars_[tmp].params().startOfAppendix()) {
566                                 recUndo(cur, tmp);
567                                 pars_[tmp].params().startOfAppendix(false);
568                                 break;
569                         }
570                 }
571
572                 cur.recordUndo();
573                 par.params().startOfAppendix(start);
574
575                 // we can set the refreshing parameters now
576                 cur.buffer()->updateLabels();
577                 break;
578         }
579
580         case LFUN_WORD_DELETE_FORWARD:
581                 if (cur.selection())
582                         cutSelection(cur, true, false);
583                 else
584                         deleteWordForward(cur);
585                 finishChange(cur, false);
586                 break;
587
588         case LFUN_WORD_DELETE_BACKWARD:
589                 if (cur.selection())
590                         cutSelection(cur, true, false);
591                 else
592                         deleteWordBackward(cur);
593                 finishChange(cur, false);
594                 break;
595
596         case LFUN_LINE_DELETE:
597                 if (cur.selection())
598                         cutSelection(cur, true, false);
599                 else
600                         tm->deleteLineForward(cur);
601                 finishChange(cur, false);
602                 break;
603
604         case LFUN_BUFFER_BEGIN:
605         case LFUN_BUFFER_BEGIN_SELECT:
606                 needsUpdate |= cur.selHandle(cmd.action == LFUN_BUFFER_BEGIN_SELECT);
607                 if (cur.depth() == 1)
608                         needsUpdate |= cursorTop(cur);
609                 else
610                         cur.undispatched();
611                 cur.updateFlags(Update::FitCursor);
612                 break;
613
614         case LFUN_BUFFER_END:
615         case LFUN_BUFFER_END_SELECT:
616                 needsUpdate |= cur.selHandle(cmd.action == LFUN_BUFFER_END_SELECT);
617                 if (cur.depth() == 1)
618                         needsUpdate |= cursorBottom(cur);
619                 else
620                         cur.undispatched();
621                 cur.updateFlags(Update::FitCursor);
622                 break;
623
624         case LFUN_INSET_BEGIN:
625         case LFUN_INSET_BEGIN_SELECT:
626                 needsUpdate |= cur.selHandle(cmd.action == LFUN_INSET_BEGIN_SELECT);
627                 if (cur.depth() == 1 || !cur.top().at_begin())
628                         needsUpdate |= cursorTop(cur);
629                 else
630                         cur.undispatched();
631                 cur.updateFlags(Update::FitCursor);
632                 break;
633
634         case LFUN_INSET_END:
635         case LFUN_INSET_END_SELECT:
636                 needsUpdate |= cur.selHandle(cmd.action == LFUN_INSET_END_SELECT);
637                 if (cur.depth() == 1 || !cur.top().at_end())
638                         needsUpdate |= cursorBottom(cur);
639                 else
640                         cur.undispatched();
641                 cur.updateFlags(Update::FitCursor);
642                 break;
643
644         case LFUN_INSET_SELECT_ALL:
645                 if (cur.depth() == 1 || !cur.selection() || !cur.selBegin().at_begin()
646                           || !cur.selEnd().at_end()) {
647                         needsUpdate |= cur.selHandle(false);
648                         needsUpdate |= cursorTop(cur);
649                         needsUpdate |= cur.selHandle(true);
650                         needsUpdate |= cursorBottom(cur);
651                 } else 
652                         cur.undispatched();
653                 cur.updateFlags(Update::FitCursor);
654                 break;
655
656         case LFUN_CHAR_FORWARD:
657         case LFUN_CHAR_FORWARD_SELECT:
658                 //LYXERR0(" LFUN_CHAR_FORWARD[SEL]:\n" << cur);
659                 needsUpdate |= cur.selHandle(cmd.action == LFUN_CHAR_FORWARD_SELECT);
660                 needsUpdate |= cursorForward(cur);
661
662                 if (!needsUpdate && oldTopSlice == cur.top()
663                                 && cur.boundary() == oldBoundary) {
664                         cur.undispatched();
665                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
666                 
667                         // we will probably be moving out the inset, so we should execute
668                         // the depm-mechanism, but only when the cursor has a place to 
669                         // go outside this inset, i.e. in a slice above.
670                         if (cur.depth() > 1 && cur.pos() == cur.lastpos() 
671                                   && cur.pit() == cur.lastpit()) {
672                                 // The cursor hasn't changed yet. To give the 
673                                 // DEPM the possibility of doing something we must
674                                 // provide it with two different cursors.
675                                 Cursor dummy = cur;
676                                 dummy.pos() = dummy.pit() = 0;
677                                 cur.bv().checkDepm(dummy, cur);
678                         }
679                 }
680                 break;
681
682         case LFUN_CHAR_BACKWARD:
683         case LFUN_CHAR_BACKWARD_SELECT:
684                 //lyxerr << "handle LFUN_CHAR_BACKWARD[_SELECT]:\n" << cur << endl;
685                 needsUpdate |= cur.selHandle(cmd.action == LFUN_CHAR_BACKWARD_SELECT);
686                 needsUpdate |= cursorBackward(cur);
687
688                 if (!needsUpdate && oldTopSlice == cur.top()
689                         && cur.boundary() == oldBoundary) {
690                         cur.undispatched();
691                         cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
692
693                         // we will probably be moving out the inset, so we should execute
694                         // the depm-mechanism, but only when the cursor has a place to 
695                         // go outside this inset, i.e. in a slice above.
696                         if (cur.depth() > 1 && cur.pos() == 0 && cur.pit() == 0) {
697                                 // The cursor hasn't changed yet. To give the 
698                                 // DEPM the possibility of doing something we must
699                                 // provide it with two different cursors.
700                                 Cursor dummy = cur;
701                                 dummy.pos() = cur.lastpos();
702                                 dummy.pit() = cur.lastpit();
703                                 cur.bv().checkDepm(dummy, cur);
704                         }
705                 }
706                 break;
707
708         case LFUN_CHAR_LEFT:
709         case LFUN_CHAR_LEFT_SELECT:
710                 if (lyxrc.visual_cursor) {
711                         needsUpdate |= cur.selHandle(cmd.action == LFUN_CHAR_LEFT_SELECT);
712                         needsUpdate |= cursorVisLeft(cur);
713                         if (!needsUpdate && oldTopSlice == cur.top()
714                                         && cur.boundary() == oldBoundary) {
715                                 cur.undispatched();
716                                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
717                         }
718                 } else {
719                         if (reverseDirectionNeeded(cur)) {
720                                 cmd.action = cmd.action == LFUN_CHAR_LEFT_SELECT ?
721                                         LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD;
722                         } else {
723                                 cmd.action = cmd.action == LFUN_CHAR_LEFT_SELECT ?
724                                         LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD;
725                         }
726                         dispatch(cur, cmd);
727                         return;
728                 }
729                 break;
730
731         case LFUN_CHAR_RIGHT:
732         case LFUN_CHAR_RIGHT_SELECT:
733                 if (lyxrc.visual_cursor) {
734                         needsUpdate |= cur.selHandle(cmd.action == LFUN_CHAR_RIGHT_SELECT);
735                         needsUpdate |= cursorVisRight(cur);
736                         if (!needsUpdate && oldTopSlice == cur.top()
737                                         && cur.boundary() == oldBoundary) {
738                                 cur.undispatched();
739                                 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
740                         }
741                 } else {
742                         if (reverseDirectionNeeded(cur)) {
743                                 cmd.action = cmd.action == LFUN_CHAR_RIGHT_SELECT ?
744                                         LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD;
745                         } else {
746                                 cmd.action = cmd.action == LFUN_CHAR_RIGHT_SELECT ?
747                                         LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD;
748                         }
749                         dispatch(cur, cmd);
750                         return;
751                 }
752                 break;
753
754
755         case LFUN_UP_SELECT:
756         case LFUN_DOWN_SELECT:
757         case LFUN_UP:
758         case LFUN_DOWN: {
759                 // stop/start the selection
760                 bool select = cmd.action == LFUN_DOWN_SELECT ||
761                         cmd.action == LFUN_UP_SELECT;
762
763                 // move cursor up/down
764                 bool up = cmd.action == LFUN_UP_SELECT || cmd.action == LFUN_UP;
765                 bool const atFirstOrLastRow = cur.atFirstOrLastRow(up);
766
767                 if (!atFirstOrLastRow) {
768                         needsUpdate |= cur.selHandle(select);   
769                         cur.selHandle(select);
770                         cur.upDownInText(up, needsUpdate);
771                         needsUpdate |= cur.beforeDispatchCursor().inMathed();
772                 } else {
773                         // if the cursor cannot be moved up or down do not remove
774                         // the selection right now, but wait for the next dispatch.
775                         if (select)
776                                 needsUpdate |= cur.selHandle(select);   
777                         cur.upDownInText(up, needsUpdate);
778                         cur.undispatched();
779                 }
780
781                 break;
782         }
783
784         case LFUN_PARAGRAPH_UP:
785         case LFUN_PARAGRAPH_UP_SELECT:
786                 needsUpdate |= cur.selHandle(cmd.action == LFUN_PARAGRAPH_UP_SELECT);
787                 needsUpdate |= cursorUpParagraph(cur);
788                 break;
789
790         case LFUN_PARAGRAPH_DOWN:
791         case LFUN_PARAGRAPH_DOWN_SELECT:
792                 needsUpdate |= cur.selHandle(cmd.action == LFUN_PARAGRAPH_DOWN_SELECT);
793                 needsUpdate |= cursorDownParagraph(cur);
794                 break;
795
796         case LFUN_LINE_BEGIN:
797         case LFUN_LINE_BEGIN_SELECT:
798                 needsUpdate |= cur.selHandle(cmd.action == LFUN_LINE_BEGIN_SELECT);
799                 needsUpdate |= tm->cursorHome(cur);
800                 break;
801
802         case LFUN_LINE_END:
803         case LFUN_LINE_END_SELECT:
804                 needsUpdate |= cur.selHandle(cmd.action == LFUN_LINE_END_SELECT);
805                 needsUpdate |= tm->cursorEnd(cur);
806                 break;
807
808         case LFUN_SECTION_SELECT: {
809                 Buffer const & buf = *cur.buffer();
810                 pit_type const pit = cur.pit();
811                 ParagraphList & pars = buf.text().paragraphs();
812                 ParagraphList::iterator bgn = pars.begin();
813                 // The first paragraph of the area to be selected:
814                 ParagraphList::iterator start = boost::next(bgn, pit);
815                 // The final paragraph of area to be selected:
816                 ParagraphList::iterator finish = start;
817                 ParagraphList::iterator end = pars.end();
818
819                 int const thistoclevel = start->layout().toclevel;
820                 if (thistoclevel == Layout::NOT_IN_TOC)
821                         break;
822
823                 cur.pos() = 0;
824                 Cursor const old_cur = cur;
825                 needsUpdate |= cur.selHandle(true);
826
827                 // Move out (down) from this section header
828                 if (finish != end)
829                         ++finish;
830
831                 // Seek the one (on same level) below
832                 for (; finish != end; ++finish, ++cur.pit()) {
833                         int const toclevel = finish->layout().toclevel;
834                         if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel)
835                                 break;
836                 }
837                 cur.pos() = cur.lastpos();
838                 
839                 needsUpdate |= cur != old_cur;
840                 break;
841         }
842
843         case LFUN_WORD_RIGHT:
844         case LFUN_WORD_RIGHT_SELECT:
845                 if (lyxrc.visual_cursor) {
846                         needsUpdate |= cur.selHandle(cmd.action == LFUN_WORD_RIGHT_SELECT);
847                         needsUpdate |= cursorVisRightOneWord(cur);
848                         if (!needsUpdate && oldTopSlice == cur.top()
849                                         && cur.boundary() == oldBoundary) {
850                                 cur.undispatched();
851                                 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
852                         }
853                 } else {
854                         if (reverseDirectionNeeded(cur)) {
855                                 cmd.action = cmd.action == LFUN_WORD_RIGHT_SELECT ?
856                                                 LFUN_WORD_BACKWARD_SELECT : LFUN_WORD_BACKWARD;
857                         } else {
858                                 cmd.action = cmd.action == LFUN_WORD_RIGHT_SELECT ?
859                                                 LFUN_WORD_FORWARD_SELECT : LFUN_WORD_FORWARD;
860                         }
861                         dispatch(cur, cmd);
862                         return;
863                 }
864                 break;
865
866         case LFUN_WORD_FORWARD:
867         case LFUN_WORD_FORWARD_SELECT:
868                 needsUpdate |= cur.selHandle(cmd.action == LFUN_WORD_FORWARD_SELECT);
869                 needsUpdate |= cursorForwardOneWord(cur);
870                 break;
871
872         case LFUN_WORD_LEFT:
873         case LFUN_WORD_LEFT_SELECT:
874                 if (lyxrc.visual_cursor) {
875                         needsUpdate |= cur.selHandle(cmd.action == LFUN_WORD_LEFT_SELECT);
876                         needsUpdate |= cursorVisLeftOneWord(cur);
877                         if (!needsUpdate && oldTopSlice == cur.top()
878                                         && cur.boundary() == oldBoundary) {
879                                 cur.undispatched();
880                                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
881                         }
882                 } else {
883                         if (reverseDirectionNeeded(cur)) {
884                                 cmd.action = cmd.action == LFUN_WORD_LEFT_SELECT ?
885                                                 LFUN_WORD_FORWARD_SELECT : LFUN_WORD_FORWARD;
886                         } else {
887                                 cmd.action = cmd.action == LFUN_WORD_LEFT_SELECT ?
888                                                 LFUN_WORD_BACKWARD_SELECT : LFUN_WORD_BACKWARD;
889                         }
890                         dispatch(cur, cmd);
891                         return;
892                 }
893                 break;
894
895         case LFUN_WORD_BACKWARD:
896         case LFUN_WORD_BACKWARD_SELECT:
897                 needsUpdate |= cur.selHandle(cmd.action == LFUN_WORD_BACKWARD_SELECT);
898                 needsUpdate |= cursorBackwardOneWord(cur);
899                 break;
900
901         case LFUN_WORD_SELECT: {
902                 selectWord(cur, WHOLE_WORD);
903                 finishChange(cur, true);
904                 break;
905         }
906
907         case LFUN_NEWLINE_INSERT: {
908                 InsetNewlineParams inp;
909                 docstring arg = cmd.argument();
910                 // this avoids a double undo
911                 // FIXME: should not be needed, ideally
912                 if (!cur.selection())
913                         cur.recordUndo();
914                 cap::replaceSelection(cur);
915                 if (arg == "linebreak")
916                         inp.kind = InsetNewlineParams::LINEBREAK;
917                 else
918                         inp.kind = InsetNewlineParams::NEWLINE;
919                 cur.insert(new InsetNewline(inp));
920                 cur.posForward();
921                 moveCursor(cur, false);
922                 break;
923         }
924
925         case LFUN_TAB_INSERT: {
926                 bool const multi_par_selection = cur.selection() &&
927                         cur.selBegin().pit() != cur.selEnd().pit();
928                 if (multi_par_selection) {
929                         // If there is a multi-paragraph selection, a tab is inserted
930                         // at the beginning of each paragraph.
931                         cur.recordUndoSelection();
932                         pit_type const pit_end = cur.selEnd().pit();
933                         for (pit_type pit = cur.selBegin().pit(); pit <= pit_end; pit++) {
934                                 pars_[pit].insertChar(0, '\t', 
935                                                       bv->buffer().params().trackChanges);
936                                 // Update the selection pos to make sure the selection does not
937                                 // change as the inserted tab will increase the logical pos.
938                                 if (cur.anchor_.pit() == pit)
939                                         cur.anchor_.forwardPos();
940                                 if (cur.pit() == pit)
941                                         cur.forwardPos();
942                         }
943                         cur.finishUndo();
944                 } else {
945                         // Maybe we shouldn't allow tabs within a line, because they
946                         // are not (yet) aligned as one might do expect.
947                         FuncRequest cmd(LFUN_SELF_INSERT, from_ascii("\t"));
948                         dispatch(cur, cmd);     
949                 }
950                 break;
951         }
952
953         case LFUN_TAB_DELETE: {
954                 bool const tc = bv->buffer().params().trackChanges;
955                 if (cur.selection()) {
956                         // If there is a selection, a tab (if present) is removed from
957                         // the beginning of each paragraph.
958                         cur.recordUndoSelection();
959                         pit_type const pit_end = cur.selEnd().pit();
960                         for (pit_type pit = cur.selBegin().pit(); pit <= pit_end; pit++) {
961                                 Paragraph & par = paragraphs()[pit];
962                                 if (par.getChar(0) == '\t') {
963                                         if (cur.pit() == pit)
964                                                 cur.posBackward();
965                                         if (cur.anchor_.pit() == pit && cur.anchor_.pos() > 0 )
966                                                 cur.anchor_.backwardPos();
967                                         
968                                         par.eraseChar(0, tc);
969                                 } else 
970                                         // If no tab was present, try to remove up to four spaces.
971                                         for (int n_spaces = 0;
972                                              par.getChar(0) == ' ' && n_spaces < 4; ++n_spaces) {
973                                                 if (cur.pit() == pit)
974                                                         cur.posBackward();
975                                                 if (cur.anchor_.pit() == pit && cur.anchor_.pos() > 0 )
976                                                         cur.anchor_.backwardPos();
977                                                 
978                                                 par.eraseChar(0, tc);
979                                         }
980                         }
981                         cur.finishUndo();
982                 } else {
983                         // If there is no selection, try to remove a tab or some spaces 
984                         // before the position of the cursor.
985                         Paragraph & par = paragraphs()[cur.pit()];
986                         pos_type const pos = cur.pos();
987                         
988                         if (pos == 0)
989                                 break;
990                         
991                         char_type const c = par.getChar(pos - 1);
992                         cur.recordUndo();
993                         if (c == '\t') {
994                                 cur.posBackward();
995                                 par.eraseChar(cur.pos(), tc);
996                         } else
997                                 for (int n_spaces = 0; 
998                                      cur.pos() > 0
999                                              && par.getChar(cur.pos() - 1) == ' ' 
1000                                              && n_spaces < 4;
1001                                      ++n_spaces) {
1002                                         cur.posBackward();
1003                                         par.eraseChar(cur.pos(), tc);
1004                                 }
1005                         cur.finishUndo();
1006                 }
1007                 break;
1008         }
1009
1010         case LFUN_CHAR_DELETE_FORWARD:
1011                 if (!cur.selection()) {
1012                         if (cur.pos() == cur.paragraph().size())
1013                                 // Par boundary, force full-screen update
1014                                 singleParUpdate = false;
1015                         needsUpdate |= erase(cur);
1016                         cur.resetAnchor();
1017                         // It is possible to make it a lot faster still
1018                         // just comment out the line below...
1019                 } else {
1020                         cutSelection(cur, true, false);
1021                         singleParUpdate = false;
1022                 }
1023                 moveCursor(cur, false);
1024                 break;
1025
1026         case LFUN_CHAR_DELETE_BACKWARD:
1027                 if (!cur.selection()) {
1028                         if (bv->getIntl().getTransManager().backspace()) {
1029                                 // Par boundary, full-screen update
1030                                 if (cur.pos() == 0)
1031                                         singleParUpdate = false;
1032                                 needsUpdate |= backspace(cur);
1033                                 cur.resetAnchor();
1034                                 // It is possible to make it a lot faster still
1035                                 // just comment out the line below...
1036                         }
1037                 } else {
1038                         cutSelection(cur, true, false);
1039                         singleParUpdate = false;
1040                 }
1041                 break;
1042
1043         case LFUN_BREAK_PARAGRAPH:
1044                 cap::replaceSelection(cur);
1045                 breakParagraph(cur, cmd.argument() == "inverse");
1046                 cur.resetAnchor();
1047                 break;
1048
1049         case LFUN_INSET_INSERT: {
1050                 cur.recordUndo();
1051
1052                 // We have to avoid triggering InstantPreview loading
1053                 // before inserting into the document. See bug #5626.
1054                 bool loaded = bv->buffer().isFullyLoaded();
1055                 bv->buffer().setFullyLoaded(false);
1056                 Inset * inset = createInset(bv->buffer(), cmd);
1057                 bv->buffer().setFullyLoaded(loaded);
1058
1059                 if (inset) {
1060                         // FIXME (Abdel 01/02/2006):
1061                         // What follows would be a partial fix for bug 2154:
1062                         //   http://bugzilla.lyx.org/show_bug.cgi?id=2154
1063                         // This automatically put the label inset _after_ a
1064                         // numbered section. It should be possible to extend the mechanism
1065                         // to any kind of LateX environement.
1066                         // The correct way to fix that bug would be at LateX generation.
1067                         // I'll let the code here for reference as it could be used for some
1068                         // other feature like "automatic labelling".
1069                         /*
1070                         Paragraph & par = pars_[cur.pit()];
1071                         if (inset->lyxCode() == LABEL_CODE
1072                                 && par.layout().labeltype == LABEL_COUNTER) {
1073                                 // Go to the end of the paragraph
1074                                 // Warning: Because of Change-Tracking, the last
1075                                 // position is 'size()' and not 'size()-1':
1076                                 cur.pos() = par.size();
1077                                 // Insert a new paragraph
1078                                 FuncRequest fr(LFUN_BREAK_PARAGRAPH);
1079                                 dispatch(cur, fr);
1080                         }
1081                         */
1082                         if (cur.selection())
1083                                 cutSelection(cur, true, false);
1084                         cur.insert(inset);
1085                         cur.posForward();
1086
1087                         // trigger InstantPreview now
1088                         if (inset->lyxCode() == EXTERNAL_CODE) {
1089                                 InsetExternal & ins =
1090                                         static_cast<InsetExternal &>(*inset);
1091                                 ins.updatePreview();
1092                         }
1093                 }
1094
1095                 break;
1096         }
1097
1098         case LFUN_INSET_DISSOLVE: {
1099                 // first, try if there's an inset at cursor
1100                 // FIXME: this first part should be moved to
1101                 // a LFUN_NEXT_INSET_DISSOLVE, or be called via
1102                 // some generic "next-inset inset-dissolve"
1103                 Inset * inset = cur.nextInset();
1104                 if (inset && inset->isActive()) {
1105                         Cursor tmpcur = cur;
1106                         tmpcur.pushBackward(*inset);
1107                         inset->dispatch(tmpcur, cmd);
1108                         if (tmpcur.result().dispatched()) {
1109                                 cur.dispatched();
1110                                 break;
1111                         }
1112                 }
1113                 // if it did not work, try the underlying inset
1114                 if (dissolveInset(cur)) {
1115                         needsUpdate = true;
1116                         break;
1117                 }
1118                 // if it did not work, do nothing.
1119                 break;
1120         }
1121
1122         case LFUN_SET_GRAPHICS_GROUP: {
1123                 InsetGraphics * ins = graphics::getCurrentGraphicsInset(cur);
1124                 if (!ins)
1125                         break;
1126
1127                 cur.recordUndo();
1128
1129                 string id = to_utf8(cmd.argument());
1130                 string grp = graphics::getGroupParams(bv->buffer(), id);
1131                 InsetGraphicsParams tmp, inspar = ins->getParams();
1132
1133                 if (id.empty())
1134                         inspar.groupId = to_utf8(cmd.argument());
1135                 else {
1136                         InsetGraphics::string2params(grp, bv->buffer(), tmp);
1137                         tmp.filename = inspar.filename;
1138                         inspar = tmp;
1139                 }
1140
1141                 ins->setParams(inspar);
1142         }
1143
1144         case LFUN_SPACE_INSERT:
1145                 if (cur.paragraph().layout().free_spacing)
1146                         insertChar(cur, ' ');
1147                 else {
1148                         doInsertInset(cur, this, cmd, false, false);
1149                         cur.posForward();
1150                 }
1151                 moveCursor(cur, false);
1152                 break;
1153
1154         case LFUN_SPECIALCHAR_INSERT: {
1155                 string const name = to_utf8(cmd.argument());
1156                 if (name == "hyphenation")
1157                         specialChar(cur, InsetSpecialChar::HYPHENATION);
1158                 else if (name == "ligature-break")
1159                         specialChar(cur, InsetSpecialChar::LIGATURE_BREAK);
1160                 else if (name == "slash")
1161                         specialChar(cur, InsetSpecialChar::SLASH);
1162                 else if (name == "nobreakdash")
1163                         specialChar(cur, InsetSpecialChar::NOBREAKDASH);
1164                 else if (name == "dots")
1165                         specialChar(cur, InsetSpecialChar::LDOTS);
1166                 else if (name == "end-of-sentence")
1167                         specialChar(cur, InsetSpecialChar::END_OF_SENTENCE);
1168                 else if (name == "menu-separator")
1169                         specialChar(cur, InsetSpecialChar::MENU_SEPARATOR);
1170                 else if (name.empty())
1171                         lyxerr << "LyX function 'specialchar-insert' needs an argument." << endl;
1172                 else
1173                         lyxerr << "Wrong argument for LyX function 'specialchar-insert'." << endl;
1174                 break;
1175         }
1176
1177         case LFUN_WORD_UPCASE:
1178                 changeCase(cur, text_uppercase);
1179                 break;
1180
1181         case LFUN_WORD_LOWCASE:
1182                 changeCase(cur, text_lowercase);
1183                 break;
1184
1185         case LFUN_WORD_CAPITALIZE:
1186                 changeCase(cur, text_capitalization);
1187                 break;
1188
1189         case LFUN_CHARS_TRANSPOSE:
1190                 charsTranspose(cur);
1191                 break;
1192
1193         case LFUN_PASTE: {
1194                 cur.message(_("Paste"));
1195                 LASSERT(cur.selBegin().idx() == cur.selEnd().idx(), /**/);
1196                 cap::replaceSelection(cur);
1197
1198                 // without argument?
1199                 string const arg = to_utf8(cmd.argument());
1200                 if (arg.empty()) {
1201                         if (theClipboard().isInternal())
1202                                 pasteFromStack(cur, bv->buffer().errorList("Paste"), 0);
1203                         else if (theClipboard().hasGraphicsContents() 
1204                                      && !theClipboard().hasTextContents())
1205                                 pasteClipboardGraphics(cur, bv->buffer().errorList("Paste"));
1206                         else
1207                                 pasteClipboardText(cur, bv->buffer().errorList("Paste"));
1208                 } else if (isStrUnsignedInt(arg)) {
1209                         // we have a numerical argument
1210                         pasteFromStack(cur, bv->buffer().errorList("Paste"),
1211                                        convert<unsigned int>(arg));
1212                 } else {
1213                         Clipboard::GraphicsType type = Clipboard::AnyGraphicsType;
1214                         if (arg == "pdf")
1215                                 type = Clipboard::PdfGraphicsType;
1216                         else if (arg == "png")
1217                                 type = Clipboard::PngGraphicsType;
1218                         else if (arg == "jpeg")
1219                                 type = Clipboard::JpegGraphicsType;
1220                         else if (arg == "linkback")
1221                                 type = Clipboard::LinkBackGraphicsType;
1222                         else if (arg == "emf")
1223                                 type = Clipboard::EmfGraphicsType;
1224                         else if (arg == "wmf")
1225                                 type = Clipboard::WmfGraphicsType;
1226
1227                         else
1228                                 LASSERT(false, /**/);
1229
1230                         pasteClipboardGraphics(cur, bv->buffer().errorList("Paste"), type);
1231                 }
1232
1233                 bv->buffer().errors("Paste");
1234                 cur.clearSelection(); // bug 393
1235                 cur.finishUndo();
1236                 break;
1237         }
1238
1239         case LFUN_CUT:
1240                 cutSelection(cur, true, true);
1241                 cur.message(_("Cut"));
1242                 break;
1243
1244         case LFUN_COPY:
1245                 copySelection(cur);
1246                 cur.message(_("Copy"));
1247                 break;
1248
1249         case LFUN_SERVER_GET_XY:
1250                 cur.message(from_utf8(
1251                         convert<string>(tm->cursorX(cur.top(), cur.boundary()))
1252                         + ' ' + convert<string>(tm->cursorY(cur.top(), cur.boundary()))));
1253                 break;
1254
1255         case LFUN_SERVER_SET_XY: {
1256                 int x = 0;
1257                 int y = 0;
1258                 istringstream is(to_utf8(cmd.argument()));
1259                 is >> x >> y;
1260                 if (!is)
1261                         lyxerr << "SETXY: Could not parse coordinates in '"
1262                                << to_utf8(cmd.argument()) << endl;
1263                 else
1264                         tm->setCursorFromCoordinates(cur, x, y);
1265                 break;
1266         }
1267
1268         case LFUN_SERVER_GET_LAYOUT:
1269                 cur.message(cur.paragraph().layout().name());
1270                 break;
1271
1272         case LFUN_LAYOUT: {
1273                 docstring layout = cmd.argument();
1274                 LYXERR(Debug::INFO, "LFUN_LAYOUT: (arg) " << to_utf8(layout));
1275
1276                 Paragraph const & para = cur.paragraph();
1277                 docstring const old_layout = para.layout().name();
1278                 DocumentClass const & tclass = bv->buffer().params().documentClass();
1279
1280                 if (layout.empty())
1281                         layout = tclass.defaultLayoutName();
1282
1283                 if (owner_->forcePlainLayout())
1284                         // in this case only the empty layout is allowed
1285                         layout = tclass.plainLayoutName();
1286                 else if (para.usePlainLayout()) {
1287                         // in this case, default layout maps to empty layout
1288                         if (layout == tclass.defaultLayoutName())
1289                                 layout = tclass.plainLayoutName();
1290                 } else {
1291                         // otherwise, the empty layout maps to the default
1292                         if (layout == tclass.plainLayoutName())
1293                                 layout = tclass.defaultLayoutName();
1294                 }
1295
1296                 bool hasLayout = tclass.hasLayout(layout);
1297
1298                 // If the entry is obsolete, use the new one instead.
1299                 if (hasLayout) {
1300                         docstring const & obs = tclass[layout].obsoleted_by();
1301                         if (!obs.empty())
1302                                 layout = obs;
1303                 }
1304
1305                 if (!hasLayout) {
1306                         cur.errorMessage(from_utf8(N_("Layout ")) + cmd.argument() +
1307                                 from_utf8(N_(" not known")));
1308                         break;
1309                 }
1310
1311                 bool change_layout = (old_layout != layout);
1312
1313                 if (!change_layout && cur.selection() &&
1314                         cur.selBegin().pit() != cur.selEnd().pit())
1315                 {
1316                         pit_type spit = cur.selBegin().pit();
1317                         pit_type epit = cur.selEnd().pit() + 1;
1318                         while (spit != epit) {
1319                                 if (pars_[spit].layout().name() != old_layout) {
1320                                         change_layout = true;
1321                                         break;
1322                                 }
1323                                 ++spit;
1324                         }
1325                 }
1326
1327                 if (change_layout)
1328                         setLayout(cur, layout);
1329
1330                 break;
1331         }
1332
1333         case LFUN_CLIPBOARD_PASTE:
1334                 cur.clearSelection();
1335                 pasteClipboardText(cur, bv->buffer().errorList("Paste"),
1336                                cmd.argument() == "paragraph");
1337                 bv->buffer().errors("Paste");
1338                 break;
1339
1340         case LFUN_PRIMARY_SELECTION_PASTE:
1341                 pasteString(cur, theSelection().get(),
1342                             cmd.argument() == "paragraph");
1343                 break;
1344
1345         case LFUN_SELECTION_PASTE:
1346                 // Copy the selection buffer to the clipboard stack,
1347                 // because we want it to appear in the "Edit->Paste
1348                 // recent" menu.
1349                 cap::copySelectionToStack();
1350                 cap::pasteSelection(bv->cursor(), bv->buffer().errorList("Paste"));
1351                 bv->buffer().errors("Paste");
1352                 break;
1353
1354         case LFUN_UNICODE_INSERT: {
1355                 if (cmd.argument().empty())
1356                         break;
1357                 docstring hexstring = cmd.argument();
1358                 if (isHex(hexstring)) {
1359                         char_type c = hexToInt(hexstring);
1360                         if (c >= 32 && c < 0x10ffff) {
1361                                 lyxerr << "Inserting c: " << c << endl;
1362                                 docstring s = docstring(1, c);
1363                                 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, s));
1364                         }
1365                 }
1366                 break;
1367         }
1368
1369         case LFUN_QUOTE_INSERT: {
1370                 Paragraph & par = cur.paragraph();
1371                 pos_type pos = cur.pos();
1372                 BufferParams const & bufparams = bv->buffer().params();
1373                 Layout const & style = par.layout();
1374                 InsetLayout const & ilayout = cur.inset().getLayout();
1375                 if (!style.pass_thru && !ilayout.isPassThru()
1376                     && par.getFontSettings(bufparams, pos).language()->lang() != "hebrew") {
1377                         // this avoids a double undo
1378                         // FIXME: should not be needed, ideally
1379                         if (!cur.selection())
1380                                 cur.recordUndo();
1381                         cap::replaceSelection(cur);
1382                         pos = cur.pos();
1383                         char_type c;
1384                         if (pos == 0)
1385                                 c = ' ';
1386                         else if (cur.prevInset() && cur.prevInset()->isSpace())
1387                                 c = ' ';
1388                         else
1389                                 c = par.getChar(pos - 1);
1390                         string arg = to_utf8(cmd.argument());
1391                         cur.insert(new InsetQuotes(bv->buffer(), c, (arg == "single")
1392                                 ? InsetQuotes::SingleQuotes : InsetQuotes::DoubleQuotes));
1393                         cur.posForward();
1394                 }
1395                 else
1396                         lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, "\""));
1397                 break;
1398         }
1399
1400         case LFUN_DATE_INSERT: {
1401                 string const format = cmd.argument().empty()
1402                         ? lyxrc.date_insert_format : to_utf8(cmd.argument());
1403                 string const time = formatted_time(current_time(), format);
1404                 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, time));
1405                 break;
1406         }
1407
1408         case LFUN_MOUSE_TRIPLE:
1409                 if (cmd.button() == mouse_button::button1) {
1410                         tm->cursorHome(cur);
1411                         cur.resetAnchor();
1412                         tm->cursorEnd(cur);
1413                         cur.setSelection();
1414                         bv->cursor() = cur;
1415                 }
1416                 break;
1417
1418         case LFUN_MOUSE_DOUBLE:
1419                 if (cmd.button() == mouse_button::button1) {
1420                         selectWord(cur, WHOLE_WORD_STRICT);
1421                         bv->cursor() = cur;
1422                 }
1423                 break;
1424
1425         // Single-click on work area
1426         case LFUN_MOUSE_PRESS:
1427                 // We are not marking a selection with the keyboard in any case.
1428                 cur.bv().cursor().setMark(false);
1429                 switch (cmd.button()) {
1430                 case mouse_button::button1:
1431                         // Set the cursor
1432                         if (!bv->mouseSetCursor(cur, cmd.argument() == "region-select"))
1433                                 cur.updateFlags(Update::SinglePar | Update::FitCursor);
1434                         break;
1435
1436                 case mouse_button::button2:
1437                         // Middle mouse pasting.
1438                         bv->mouseSetCursor(cur);
1439                         lyx::dispatch(
1440                                 FuncRequest(LFUN_COMMAND_ALTERNATIVES,
1441                                             "selection-paste ; primary-selection-paste paragraph"));
1442                         cur.noUpdate();
1443                         break;
1444
1445                 case mouse_button::button3: {
1446                         Cursor const & bvcur = cur.bv().cursor();
1447                         // Don't do anything if we right-click a
1448                         // selection, a context menu will popup.
1449                         if (bvcur.selection() && cur >= bvcur.selectionBegin()
1450                             && cur < bvcur.selectionEnd()) {
1451                                 cur.noUpdate();
1452                                 return;
1453                         }
1454                         if (!bv->mouseSetCursor(cur, false))
1455                                 cur.updateFlags(Update::SinglePar | Update::FitCursor);
1456                         break;
1457                 }
1458
1459                 default:
1460                         break;
1461                 } // switch (cmd.button())
1462                 break;
1463
1464         case LFUN_MOUSE_MOTION: {
1465                 // Mouse motion with right or middle mouse do nothing for now.
1466                 if (cmd.button() != mouse_button::button1) {
1467                         cur.noUpdate();
1468                         return;
1469                 }
1470                 // ignore motions deeper nested than the real anchor
1471                 Cursor & bvcur = cur.bv().cursor();
1472                 if (!bvcur.anchor_.hasPart(cur)) {
1473                         cur.undispatched();
1474                         break;
1475                 }
1476                 CursorSlice old = bvcur.top();
1477
1478                 int const wh = bv->workHeight();
1479                 int const y = max(0, min(wh - 1, cmd.y));
1480
1481                 tm->setCursorFromCoordinates(cur, cmd.x, y);
1482                 cur.setTargetX(cmd.x);
1483                 if (cmd.y >= wh)
1484                         lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1485                 else if (cmd.y < 0)
1486                         lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1487                 // This is to allow jumping over large insets
1488                 if (cur.top() == old) {
1489                         if (cmd.y >= wh)
1490                                 lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1491                         else if (cmd.y < 0)
1492                                 lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1493                 }
1494                 // We continue with our existing selection or start a new one, so don't
1495                 // reset the anchor.
1496                 bvcur.setCursor(cur);
1497                 bvcur.setSelection(true);
1498                 if (cur.top() == old) {
1499                         // We didn't move one iota, so no need to update the screen.
1500                         cur.updateFlags(Update::SinglePar | Update::FitCursor);
1501                         //cur.noUpdate();
1502                         return;
1503                 }
1504                 break;
1505         }
1506
1507         case LFUN_MOUSE_RELEASE:
1508                 switch (cmd.button()) {
1509                 case mouse_button::button1:
1510                         // Cursor was set at LFUN_MOUSE_PRESS or LFUN_MOUSE_MOTION time.
1511                         // If there is a new selection, update persistent selection;
1512                         // otherwise, single click does not clear persistent selection
1513                         // buffer.
1514                         if (cur.selection()) {
1515                                 // Finish selection. If double click,
1516                                 // cur is moved to the end of word by
1517                                 // selectWord but bvcur is current
1518                                 // mouse position.
1519                                 cur.bv().cursor().setSelection();
1520                                 // We might have removed an empty but drawn selection
1521                                 // (probably a margin)
1522                                 cur.updateFlags(Update::SinglePar | Update::FitCursor);
1523                         } else
1524                                 cur.noUpdate();
1525                         // FIXME: We could try to handle drag and drop of selection here.
1526                         return;
1527
1528                 case mouse_button::button2:
1529                         // Middle mouse pasting is handled at mouse press time,
1530                         // see LFUN_MOUSE_PRESS.
1531                         cur.noUpdate();
1532                         return;
1533
1534                 case mouse_button::button3:
1535                         // Cursor was set at LFUN_MOUSE_PRESS time.
1536                         // FIXME: If there is a selection we could try to handle a special
1537                         // drag & drop context menu.
1538                         cur.noUpdate();
1539                         return;
1540
1541                 case mouse_button::none:
1542                 case mouse_button::button4:
1543                 case mouse_button::button5:
1544                         break;
1545                 } // switch (cmd.button())
1546
1547                 break;
1548
1549         case LFUN_SELF_INSERT: {
1550                 if (cmd.argument().empty())
1551                         break;
1552
1553                 // Automatically delete the currently selected
1554                 // text and replace it with what is being
1555                 // typed in now. Depends on lyxrc settings
1556                 // "auto_region_delete", which defaults to
1557                 // true (on).
1558
1559                 if (lyxrc.auto_region_delete && cur.selection())
1560                         cutSelection(cur, false, false);
1561
1562                 cur.clearSelection();
1563
1564                 docstring::const_iterator cit = cmd.argument().begin();
1565                 docstring::const_iterator const end = cmd.argument().end();
1566                 for (; cit != end; ++cit)
1567                         bv->translateAndInsert(*cit, this, cur);
1568
1569                 cur.resetAnchor();
1570                 moveCursor(cur, false);
1571                 bv->bookmarkEditPosition();
1572                 break;
1573         }
1574
1575         case LFUN_HYPERLINK_INSERT: {
1576                 InsetCommandParams p(HYPERLINK_CODE);
1577                 docstring content;
1578                 if (cur.selection()) {
1579                         content = cur.selectionAsString(false);
1580                         cutSelection(cur, true, false);
1581                 }
1582                 p["target"] = (cmd.argument().empty()) ?
1583                         content : cmd.argument();
1584                 string const data = InsetCommand::params2string("href", p);
1585                 if (p["target"].empty()) {
1586                         bv->showDialog("href", data);
1587                 } else {
1588                         FuncRequest fr(LFUN_INSET_INSERT, data);
1589                         dispatch(cur, fr);
1590                 }
1591                 break;
1592         }
1593
1594         case LFUN_LABEL_INSERT: {
1595                 InsetCommandParams p(LABEL_CODE);
1596                 // Try to generate a valid label
1597                 p["name"] = (cmd.argument().empty()) ?
1598                         cur.getPossibleLabel() :
1599                         cmd.argument();
1600                 string const data = InsetCommand::params2string("label", p);
1601
1602                 if (cmd.argument().empty()) {
1603                         bv->showDialog("label", data);
1604                 } else {
1605                         FuncRequest fr(LFUN_INSET_INSERT, data);
1606                         dispatch(cur, fr);
1607                 }
1608                 break;
1609         }
1610
1611         case LFUN_INFO_INSERT: {
1612                 Inset * inset;
1613                 if (cmd.argument().empty() && cur.selection()) {
1614                         // if command argument is empty use current selection as parameter.
1615                         docstring ds = cur.selectionAsString(false);
1616                         cutSelection(cur, true, false);
1617                         FuncRequest cmd0(cmd, ds);
1618                         inset = createInset(cur.bv().buffer(), cmd0);
1619                 } else {
1620                         inset = createInset(cur.bv().buffer(), cmd);
1621                 }
1622                 if (!inset)
1623                         break;
1624                 cur.recordUndo();
1625                 insertInset(cur, inset);
1626                 cur.posForward();
1627                 break;
1628         }
1629         case LFUN_CAPTION_INSERT:
1630         case LFUN_FOOTNOTE_INSERT:
1631         case LFUN_NOTE_INSERT:
1632         case LFUN_FLEX_INSERT:
1633         case LFUN_BOX_INSERT:
1634         case LFUN_BRANCH_INSERT:
1635         case LFUN_PHANTOM_INSERT:
1636         case LFUN_ERT_INSERT:
1637         case LFUN_LISTING_INSERT:
1638         case LFUN_MARGINALNOTE_INSERT:
1639         case LFUN_OPTIONAL_INSERT:
1640         case LFUN_INDEX_INSERT:
1641                 // Open the inset, and move the current selection
1642                 // inside it.
1643                 doInsertInset(cur, this, cmd, true, true);
1644                 cur.posForward();
1645                 // Some insets are numbered, others are shown in the outline pane so
1646                 // let's update the labels and the toc backend.
1647                 bv->buffer().updateLabels();
1648                 break;
1649
1650         case LFUN_TABULAR_INSERT:
1651                 // if there were no arguments, just open the dialog
1652                 if (doInsertInset(cur, this, cmd, false, true))
1653                         cur.posForward();
1654                 else
1655                         bv->showDialog("tabularcreate");
1656
1657                 break;
1658
1659         case LFUN_FLOAT_INSERT:
1660         case LFUN_FLOAT_WIDE_INSERT:
1661         case LFUN_WRAP_INSERT: {
1662                 // will some text be moved into the inset?
1663                 bool content = cur.selection();
1664
1665                 doInsertInset(cur, this, cmd, true, true);
1666                 cur.posForward();
1667
1668                 // If some text is moved into the inset, doInsertInset 
1669                 // puts the cursor outside the inset. To insert the
1670                 // caption we put it back into the inset.
1671                 if (content)
1672                         cur.backwardPos();
1673
1674                 ParagraphList & pars = cur.text()->paragraphs();
1675
1676                 DocumentClass const & tclass = bv->buffer().params().documentClass();
1677
1678                 // add a separate paragraph for the caption inset
1679                 pars.push_back(Paragraph());
1680                 pars.back().setInsetOwner(&cur.text()->inset());
1681                 pars.back().setPlainOrDefaultLayout(tclass);
1682                 int cap_pit = pars.size() - 1;
1683
1684                 // if an empty inset was created, we create an additional empty
1685                 // paragraph at the bottom so that the user can choose where to put
1686                 // the graphics (or table).
1687                 if (!content) {
1688                         pars.push_back(Paragraph());
1689                         pars.back().setInsetOwner(&cur.text()->inset());
1690                         pars.back().setPlainOrDefaultLayout(tclass);
1691                 }
1692
1693                 // reposition the cursor to the caption
1694                 cur.pit() = cap_pit;
1695                 cur.pos() = 0;
1696                 // FIXME: This Text/Cursor dispatch handling is a mess!
1697                 // We cannot use Cursor::dispatch here it needs access to up to
1698                 // date metrics.
1699                 FuncRequest cmd_caption(LFUN_CAPTION_INSERT);
1700                 doInsertInset(cur, cur.text(), cmd_caption, true, false);
1701                 bv->buffer().updateLabels();
1702                 cur.updateFlags(Update::Force);
1703                 // FIXME: When leaving the Float (or Wrap) inset we should
1704                 // delete any empty paragraph left above or below the
1705                 // caption.
1706                 break;
1707         }
1708
1709         case LFUN_NOMENCL_INSERT: {
1710                 InsetCommandParams p(NOMENCL_CODE);
1711                 if (cmd.argument().empty())
1712                         p["symbol"] = bv->cursor().innerText()->getStringToIndex(bv->cursor());
1713                 else
1714                         p["symbol"] = cmd.argument();
1715                 string const data = InsetCommand::params2string("nomenclature", p);
1716                 bv->showDialog("nomenclature", data);
1717                 break;
1718         }
1719
1720         case LFUN_INDEX_PRINT: {
1721                 InsetCommandParams p(INDEX_PRINT_CODE);
1722                 if (cmd.argument().empty())
1723                         p["type"] = from_ascii("idx");
1724                 else
1725                         p["type"] = cmd.argument();
1726                 string const data = InsetCommand::params2string("index_print", p);
1727                 FuncRequest fr(LFUN_INSET_INSERT, data);
1728                 dispatch(cur, fr);
1729                 break;
1730         }
1731         
1732         case LFUN_NOMENCL_PRINT:
1733         case LFUN_TOC_INSERT:
1734         case LFUN_LINE_INSERT:
1735         case LFUN_NEWPAGE_INSERT:
1736                 // do nothing fancy
1737                 doInsertInset(cur, this, cmd, false, false);
1738                 cur.posForward();
1739                 break;
1740
1741         case LFUN_DEPTH_DECREMENT:
1742                 changeDepth(cur, DEC_DEPTH);
1743                 break;
1744
1745         case LFUN_DEPTH_INCREMENT:
1746                 changeDepth(cur, INC_DEPTH);
1747                 break;
1748
1749         case LFUN_MATH_DISPLAY:
1750                 mathDispatch(cur, cmd, true);
1751                 break;
1752
1753         case LFUN_REGEXP_MODE:
1754                 regexpDispatch(cur, cmd);
1755                 break;
1756
1757         case LFUN_MATH_MODE:
1758                 if (cmd.argument() == "on")
1759                         // don't pass "on" as argument
1760                         mathDispatch(cur, FuncRequest(LFUN_MATH_MODE), false);
1761                 else
1762                         mathDispatch(cur, cmd, false);
1763                 break;
1764
1765         case LFUN_MATH_MACRO:
1766                 if (cmd.argument().empty())
1767                         cur.errorMessage(from_utf8(N_("Missing argument")));
1768                 else {
1769                         string s = to_utf8(cmd.argument());
1770                         string const s1 = token(s, ' ', 1);
1771                         int const nargs = s1.empty() ? 0 : convert<int>(s1);
1772                         string const s2 = token(s, ' ', 2);
1773                         MacroType type = MacroTypeNewcommand;
1774                         if (s2 == "def")
1775                                 type = MacroTypeDef;
1776                         MathMacroTemplate * inset = new MathMacroTemplate(from_utf8(token(s, ' ', 0)), nargs, false, type);
1777                         inset->setBuffer(bv->buffer());
1778                         insertInset(cur, inset);
1779
1780                         // enter macro inset and select the name
1781                         cur.push(*inset);
1782                         cur.top().pos() = cur.top().lastpos();
1783                         cur.resetAnchor();
1784                         cur.setSelection(true);
1785                         cur.top().pos() = 0;
1786                 }
1787                 break;
1788
1789         // passthrough hat and underscore outside mathed:
1790         case LFUN_MATH_SUBSCRIPT:
1791                 mathDispatch(cur, FuncRequest(LFUN_SELF_INSERT, "_"), false);
1792                 break;
1793         case LFUN_MATH_SUPERSCRIPT:
1794                 mathDispatch(cur, FuncRequest(LFUN_SELF_INSERT, "^"), false);
1795                 break;
1796
1797         case LFUN_MATH_INSERT:
1798         case LFUN_MATH_AMS_MATRIX:
1799         case LFUN_MATH_MATRIX:
1800         case LFUN_MATH_DELIM:
1801         case LFUN_MATH_BIGDELIM: {
1802                 cur.recordUndo();
1803                 cap::replaceSelection(cur);
1804                 cur.insert(new InsetMathHull(hullSimple));
1805                 checkAndActivateInset(cur, true);
1806                 LASSERT(cur.inMathed(), /**/);
1807                 cur.dispatch(cmd);
1808                 break;
1809         }
1810
1811         case LFUN_FONT_EMPH: {
1812                 Font font(ignore_font, ignore_language);
1813                 font.fontInfo().setEmph(FONT_TOGGLE);
1814                 toggleAndShow(cur, this, font);
1815                 break;
1816         }
1817
1818         case LFUN_FONT_ITAL: {
1819                 Font font(ignore_font, ignore_language);
1820                 font.fontInfo().setShape(ITALIC_SHAPE);
1821                 toggleAndShow(cur, this, font);
1822                 break;
1823         }
1824
1825         case LFUN_FONT_BOLD:
1826         case LFUN_FONT_BOLDSYMBOL: {
1827                 Font font(ignore_font, ignore_language);
1828                 font.fontInfo().setSeries(BOLD_SERIES);
1829                 toggleAndShow(cur, this, font);
1830                 break;
1831         }
1832
1833         case LFUN_FONT_NOUN: {
1834                 Font font(ignore_font, ignore_language);
1835                 font.fontInfo().setNoun(FONT_TOGGLE);
1836                 toggleAndShow(cur, this, font);
1837                 break;
1838         }
1839
1840         case LFUN_FONT_TYPEWRITER: {
1841                 Font font(ignore_font, ignore_language);
1842                 font.fontInfo().setFamily(TYPEWRITER_FAMILY); // no good
1843                 toggleAndShow(cur, this, font);
1844                 break;
1845         }
1846
1847         case LFUN_FONT_SANS: {
1848                 Font font(ignore_font, ignore_language);
1849                 font.fontInfo().setFamily(SANS_FAMILY);
1850                 toggleAndShow(cur, this, font);
1851                 break;
1852         }
1853
1854         case LFUN_FONT_ROMAN: {
1855                 Font font(ignore_font, ignore_language);
1856                 font.fontInfo().setFamily(ROMAN_FAMILY);
1857                 toggleAndShow(cur, this, font);
1858                 break;
1859         }
1860
1861         case LFUN_FONT_DEFAULT: {
1862                 Font font(inherit_font, ignore_language);
1863                 toggleAndShow(cur, this, font);
1864                 break;
1865         }
1866
1867         case LFUN_FONT_STRIKEOUT: {
1868                 Font font(ignore_font, ignore_language);
1869                 font.fontInfo().setStrikeout(FONT_TOGGLE);
1870                 toggleAndShow(cur, this, font);
1871                 break;
1872         }
1873
1874         case LFUN_FONT_UULINE: {
1875                 Font font(ignore_font, ignore_language);
1876                 font.fontInfo().setUuline(FONT_TOGGLE);
1877                 toggleAndShow(cur, this, font);
1878                 break;
1879         }
1880
1881         case LFUN_FONT_UWAVE: {
1882                 Font font(ignore_font, ignore_language);
1883                 font.fontInfo().setUwave(FONT_TOGGLE);
1884                 toggleAndShow(cur, this, font);
1885                 break;
1886         }
1887
1888         case LFUN_FONT_UNDERLINE: {
1889                 Font font(ignore_font, ignore_language);
1890                 font.fontInfo().setUnderbar(FONT_TOGGLE);
1891                 toggleAndShow(cur, this, font);
1892                 break;
1893         }
1894
1895         case LFUN_FONT_SIZE: {
1896                 Font font(ignore_font, ignore_language);
1897                 setLyXSize(to_utf8(cmd.argument()), font.fontInfo());
1898                 toggleAndShow(cur, this, font);
1899                 break;
1900         }
1901
1902         case LFUN_LANGUAGE: {
1903                 Language const * lang = languages.getLanguage(to_utf8(cmd.argument()));
1904                 if (!lang)
1905                         break;
1906                 Font font(ignore_font, lang);
1907                 toggleAndShow(cur, this, font);
1908                 break;
1909         }
1910
1911         case LFUN_TEXTSTYLE_APPLY:
1912                 toggleAndShow(cur, this, freefont, toggleall);
1913                 cur.message(_("Character set"));
1914                 break;
1915
1916         // Set the freefont using the contents of \param data dispatched from
1917         // the frontends and apply it at the current cursor location.
1918         case LFUN_TEXTSTYLE_UPDATE: {
1919                 Font font;
1920                 bool toggle;
1921                 if (font.fromString(to_utf8(cmd.argument()), toggle)) {
1922                         freefont = font;
1923                         toggleall = toggle;
1924                         toggleAndShow(cur, this, freefont, toggleall);
1925                         cur.message(_("Character set"));
1926                 } else {
1927                         lyxerr << "Argument not ok";
1928                 }
1929                 break;
1930         }
1931
1932         case LFUN_FINISHED_LEFT:
1933                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_LEFT:\n" << cur);
1934                 // We're leaving an inset, going left. If the inset is LTR, we're
1935                 // leaving from the front, so we should not move (remain at --- but
1936                 // not in --- the inset). If the inset is RTL, move left, without
1937                 // entering the inset itself; i.e., move to after the inset.
1938                 if (cur.paragraph().getFontSettings(
1939                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
1940                         cursorVisLeft(cur, true);
1941                 break;
1942
1943         case LFUN_FINISHED_RIGHT:
1944                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_RIGHT:\n" << cur);
1945                 // We're leaving an inset, going right. If the inset is RTL, we're
1946                 // leaving from the front, so we should not move (remain at --- but
1947                 // not in --- the inset). If the inset is LTR, move right, without
1948                 // entering the inset itself; i.e., move to after the inset.
1949                 if (!cur.paragraph().getFontSettings(
1950                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
1951                         cursorVisRight(cur, true);
1952                 break;
1953
1954         case LFUN_FINISHED_BACKWARD:
1955                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_BACKWARD:\n" << cur);
1956                 break;
1957
1958         case LFUN_FINISHED_FORWARD:
1959                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_FORWARD:\n" << cur);
1960                 ++cur.pos();
1961                 cur.setCurrentFont();
1962                 break;
1963
1964         case LFUN_LAYOUT_PARAGRAPH: {
1965                 string data;
1966                 params2string(cur.paragraph(), data);
1967                 data = "show\n" + data;
1968                 bv->showDialog("paragraph", data);
1969                 break;
1970         }
1971
1972         case LFUN_PARAGRAPH_UPDATE: {
1973                 string data;
1974                 params2string(cur.paragraph(), data);
1975
1976                 // Will the paragraph accept changes from the dialog?
1977                 bool const accept =
1978                         cur.inset().allowParagraphCustomization(cur.idx());
1979
1980                 data = "update " + convert<string>(accept) + '\n' + data;
1981                 bv->updateDialog("paragraph", data);
1982                 break;
1983         }
1984
1985         case LFUN_ACCENT_UMLAUT:
1986         case LFUN_ACCENT_CIRCUMFLEX:
1987         case LFUN_ACCENT_GRAVE:
1988         case LFUN_ACCENT_ACUTE:
1989         case LFUN_ACCENT_TILDE:
1990         case LFUN_ACCENT_CEDILLA:
1991         case LFUN_ACCENT_MACRON:
1992         case LFUN_ACCENT_DOT:
1993         case LFUN_ACCENT_UNDERDOT:
1994         case LFUN_ACCENT_UNDERBAR:
1995         case LFUN_ACCENT_CARON:
1996         case LFUN_ACCENT_BREVE:
1997         case LFUN_ACCENT_TIE:
1998         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
1999         case LFUN_ACCENT_CIRCLE:
2000         case LFUN_ACCENT_OGONEK:
2001                 theLyXFunc().handleKeyFunc(cmd.action);
2002                 if (!cmd.argument().empty())
2003                         // FIXME: Are all these characters encoded in one byte in utf8?
2004                         bv->translateAndInsert(cmd.argument()[0], this, cur);
2005                 break;
2006
2007         case LFUN_FLOAT_LIST_INSERT: {
2008                 DocumentClass const & tclass = bv->buffer().params().documentClass();
2009                 if (tclass.floats().typeExist(to_utf8(cmd.argument()))) {
2010                         cur.recordUndo();
2011                         if (cur.selection())
2012                                 cutSelection(cur, true, false);
2013                         breakParagraph(cur);
2014
2015                         if (cur.lastpos() != 0) {
2016                                 cursorBackward(cur);
2017                                 breakParagraph(cur);
2018                         }
2019
2020                         docstring const laystr = cur.inset().usePlainLayout() ?
2021                                 tclass.plainLayoutName() :
2022                                 tclass.defaultLayoutName();
2023                         setLayout(cur, laystr);
2024                         ParagraphParameters p;
2025                         // FIXME If this call were replaced with one to clearParagraphParams(),
2026                         // then we could get rid of this method altogether.
2027                         setParagraphs(cur, p);
2028                         // FIXME This should be simplified when InsetFloatList takes a
2029                         // Buffer in its constructor.
2030                         InsetFloatList * ifl = new InsetFloatList(to_utf8(cmd.argument()));
2031                         ifl->setBuffer(bv->buffer());
2032                         insertInset(cur, ifl);
2033                         cur.posForward();
2034                 } else {
2035                         lyxerr << "Non-existent float type: "
2036                                << to_utf8(cmd.argument()) << endl;
2037                 }
2038                 break;
2039         }
2040
2041         case LFUN_CHANGE_ACCEPT: {
2042                 acceptOrRejectChanges(cur, ACCEPT);
2043                 break;
2044         }
2045
2046         case LFUN_CHANGE_REJECT: {
2047                 acceptOrRejectChanges(cur, REJECT);
2048                 break;
2049         }
2050
2051         case LFUN_THESAURUS_ENTRY: {
2052                 docstring arg = cmd.argument();
2053                 if (arg.empty()) {
2054                         arg = cur.selectionAsString(false);
2055                         // FIXME
2056                         if (arg.size() > 100 || arg.empty()) {
2057                                 // Get word or selection
2058                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2059                                 arg = cur.selectionAsString(false);
2060                                 arg += " lang=" + from_ascii(cur.getFont().language()->lang());
2061                         }
2062                 }
2063                 bv->showDialog("thesaurus", to_utf8(arg));
2064                 break;
2065         }
2066
2067         case LFUN_PARAGRAPH_PARAMS_APPLY: {
2068                 // Given data, an encoding of the ParagraphParameters
2069                 // generated in the Paragraph dialog, this function sets
2070                 // the current paragraph, or currently selected paragraphs,
2071                 // appropriately.
2072                 // NOTE: This function overrides all existing settings.
2073                 setParagraphs(cur, cmd.argument());
2074                 cur.message(_("Paragraph layout set"));
2075                 break;
2076         }
2077
2078         case LFUN_PARAGRAPH_PARAMS: {
2079                 // Given data, an encoding of the ParagraphParameters as we'd
2080                 // find them in a LyX file, this function modifies the current paragraph,
2081                 // or currently selected paragraphs.
2082                 // NOTE: This function only modifies, and does not override, existing
2083                 // settings.
2084                 setParagraphs(cur, cmd.argument(), true);
2085                 cur.message(_("Paragraph layout set"));
2086                 break;
2087         }
2088
2089         case LFUN_ESCAPE:
2090                 if (cur.selection()) {
2091                         cur.setSelection(false);
2092                 } else {
2093                         cur.undispatched();
2094                         // This used to be LFUN_FINISHED_RIGHT, I think FORWARD is more
2095                         // correct, but I'm not 100% sure -- dov, 071019
2096                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
2097                 }
2098                 break;
2099
2100         case LFUN_OUTLINE_UP:
2101                 outline(OutlineUp, cur);
2102                 setCursor(cur, cur.pit(), 0);
2103                 cur.buffer()->updateLabels();
2104                 needsUpdate = true;
2105                 break;
2106
2107         case LFUN_OUTLINE_DOWN:
2108                 outline(OutlineDown, cur);
2109                 setCursor(cur, cur.pit(), 0);
2110                 cur.buffer()->updateLabels();
2111                 needsUpdate = true;
2112                 break;
2113
2114         case LFUN_OUTLINE_IN:
2115                 outline(OutlineIn, cur);
2116                 cur.buffer()->updateLabels();
2117                 needsUpdate = true;
2118                 break;
2119
2120         case LFUN_OUTLINE_OUT:
2121                 outline(OutlineOut, cur);
2122                 cur.buffer()->updateLabels();
2123                 needsUpdate = true;
2124                 break;
2125         
2126         case LFUN_OUTLINE_DRAGMOVE: {
2127                 int const move_id = convert<int>(cmd.getArg(0));
2128                 int const move_to_id = convert<int>(cmd.getArg(1));
2129                 dragMove(cur, move_id, move_to_id);
2130                 setCursor(cur, cur.pit(), 0);
2131                 cur.buffer()->updateLabels();
2132                 needsUpdate = true;
2133                 break;
2134         }
2135
2136         default:
2137                 LYXERR(Debug::ACTION, "Command " << cmd << " not DISPATCHED by Text");
2138                 cur.undispatched();
2139                 break;
2140         }
2141
2142         needsUpdate |= (cur.pos() != cur.lastpos()) && cur.selection();
2143
2144         // FIXME: The cursor flag is reset two lines below
2145         // so we need to check here if some of the LFUN did touch that.
2146         // for now only Text::erase() and Text::backspace() do that.
2147         // The plan is to verify all the LFUNs and then to remove this
2148         // singleParUpdate boolean altogether.
2149         if (cur.result().update() & Update::Force) {
2150                 singleParUpdate = false;
2151                 needsUpdate = true;
2152         }
2153
2154         // FIXME: the following code should go in favor of fine grained
2155         // update flag treatment.
2156         if (singleParUpdate) {
2157                 // Inserting characters does not change par height in general. So, try
2158                 // to update _only_ this paragraph. BufferView will detect if a full
2159                 // metrics update is needed anyway.
2160                 cur.updateFlags(Update::SinglePar | Update::FitCursor);
2161                 return;
2162         }
2163
2164         if (!needsUpdate
2165             && &oldTopSlice.inset() == &cur.inset()
2166             && oldTopSlice.idx() == cur.idx()
2167             && !sel // sel is a backup of cur.selection() at the beginning of the function.
2168             && !cur.selection())
2169                 // FIXME: it would be better if we could just do this
2170                 //
2171                 //if (cur.result().update() != Update::FitCursor)
2172                 //      cur.noUpdate();
2173                 //
2174                 // But some LFUNs do not set Update::FitCursor when needed, so we
2175                 // do it for all. This is not very harmfull as FitCursor will provoke
2176                 // a full redraw only if needed but still, a proper review of all LFUN
2177                 // should be done and this needsUpdate boolean can then be removed.
2178                 cur.updateFlags(Update::FitCursor);
2179         else
2180                 cur.updateFlags(Update::Force | Update::FitCursor);
2181 }
2182
2183
2184 bool Text::getStatus(Cursor & cur, FuncRequest const & cmd,
2185                         FuncStatus & flag) const
2186 {
2187         LASSERT(cur.text() == this, /**/);
2188
2189         FontInfo const & fontinfo = cur.real_current_font.fontInfo();
2190         bool enable = true;
2191         InsetCode code = NO_CODE;
2192
2193         switch (cmd.action) {
2194
2195         case LFUN_DEPTH_DECREMENT:
2196                 enable = changeDepthAllowed(cur, DEC_DEPTH);
2197                 break;
2198
2199         case LFUN_DEPTH_INCREMENT:
2200                 enable = changeDepthAllowed(cur, INC_DEPTH);
2201                 break;
2202
2203         case LFUN_APPENDIX:
2204                 flag.setOnOff(cur.paragraph().params().startOfAppendix());
2205                 break;
2206
2207         case LFUN_DIALOG_SHOW_NEW_INSET:
2208                 if (cmd.argument() == "bibitem")
2209                         code = BIBITEM_CODE;
2210                 else if (cmd.argument() == "bibtex") {
2211                         code = BIBTEX_CODE;
2212                         // not allowed in description items
2213                         enable = !inDescriptionItem(cur);
2214                 }
2215                 else if (cmd.argument() == "box")
2216                         code = BOX_CODE;
2217                 else if (cmd.argument() == "branch")
2218                         code = BRANCH_CODE;
2219                 else if (cmd.argument() == "citation")
2220                         code = CITE_CODE;
2221                 else if (cmd.argument() == "ert")
2222                         code = ERT_CODE;
2223                 else if (cmd.argument() == "external")
2224                         code = EXTERNAL_CODE;
2225                 else if (cmd.argument() == "float")
2226                         code = FLOAT_CODE;
2227                 else if (cmd.argument() == "graphics")
2228                         code = GRAPHICS_CODE;
2229                 else if (cmd.argument() == "href")
2230                         code = HYPERLINK_CODE;
2231                 else if (cmd.argument() == "include")
2232                         code = INCLUDE_CODE;
2233                 else if (cmd.argument() == "index")
2234                         code = INDEX_CODE;
2235                 else if (cmd.argument() == "index_print")
2236                         code = INDEX_PRINT_CODE;
2237                 else if (cmd.argument() == "nomenclature")
2238                         code = NOMENCL_CODE;
2239                 else if (cmd.argument() == "nomencl_print")
2240                         code = NOMENCL_PRINT_CODE;
2241                 else if (cmd.argument() == "label")
2242                         code = LABEL_CODE;
2243                 else if (cmd.argument() == "note")
2244                         code = NOTE_CODE;
2245                 else if (cmd.argument() == "phantom")
2246                         code = PHANTOM_CODE;
2247                 else if (cmd.argument() == "ref")
2248                         code = REF_CODE;
2249                 else if (cmd.argument() == "space")
2250                         code = SPACE_CODE;
2251                 else if (cmd.argument() == "toc")
2252                         code = TOC_CODE;
2253                 else if (cmd.argument() == "vspace")
2254                         code = VSPACE_CODE;
2255                 else if (cmd.argument() == "wrap")
2256                         code = WRAP_CODE;
2257                 else if (cmd.argument() == "listings")
2258                         code = LISTINGS_CODE;
2259                 break;
2260
2261         case LFUN_ERT_INSERT:
2262                 code = ERT_CODE;
2263                 break;
2264         case LFUN_LISTING_INSERT:
2265                 code = LISTINGS_CODE;
2266                 // not allowed in description items
2267                 enable = !inDescriptionItem(cur);
2268                 break;
2269         case LFUN_FOOTNOTE_INSERT:
2270                 code = FOOT_CODE;
2271                 break;
2272         case LFUN_TABULAR_INSERT:
2273                 code = TABULAR_CODE;
2274                 break;
2275         case LFUN_MARGINALNOTE_INSERT:
2276                 code = MARGIN_CODE;
2277                 break;
2278         case LFUN_FLOAT_INSERT:
2279         case LFUN_FLOAT_WIDE_INSERT:
2280                 // FIXME: If there is a selection, we should check whether there
2281                 // are floats in the selection, but this has performance issues, see
2282                 // LFUN_CHANGE_ACCEPT/REJECT.
2283                 code = FLOAT_CODE;
2284                 if (inDescriptionItem(cur))
2285                         // not allowed in description items
2286                         enable = false;
2287                 else {
2288                         InsetCode const inset_code = cur.inset().lyxCode();
2289
2290                         // algorithm floats cannot be put in another float
2291                         if (to_utf8(cmd.argument()) == "algorithm") {
2292                                 enable = inset_code != WRAP_CODE && inset_code != FLOAT_CODE;
2293                                 break;
2294                         }
2295
2296                         // for figures and tables: only allow in another
2297                         // float or wrap if it is of the same type and
2298                         // not a subfloat already
2299                         if(cur.inset().lyxCode() == code) {
2300                                 InsetFloat const & ins =
2301                                         static_cast<InsetFloat const &>(cur.inset());
2302                                 enable = ins.params().type == to_utf8(cmd.argument())
2303                                         && !ins.params().subfloat;
2304                         } else if(cur.inset().lyxCode() == WRAP_CODE) {
2305                                 InsetWrap const & ins =
2306                                         static_cast<InsetWrap const &>(cur.inset());
2307                                 enable = ins.params().type == to_utf8(cmd.argument());
2308                         }
2309                 }
2310                 break;
2311         case LFUN_WRAP_INSERT:
2312                 code = WRAP_CODE;
2313                 // not allowed in description items
2314                 enable = !inDescriptionItem(cur);
2315                 break;
2316         case LFUN_FLOAT_LIST_INSERT:
2317                 code = FLOAT_LIST_CODE;
2318                 // not allowed in description items
2319                 enable = !inDescriptionItem(cur);
2320                 break;
2321         case LFUN_CAPTION_INSERT:
2322                 code = CAPTION_CODE;
2323                 // not allowed in description items
2324                 enable = !inDescriptionItem(cur);
2325                 break;
2326         case LFUN_NOTE_INSERT:
2327                 code = NOTE_CODE;
2328                 // in commands (sections etc.) and description items,
2329                 // only Notes are allowed
2330                 enable = (cmd.argument().empty() || cmd.getArg(0) == "Note" ||
2331                           (!cur.paragraph().layout().isCommand()
2332                            && !inDescriptionItem(cur)));
2333                 break;
2334         case LFUN_FLEX_INSERT: {
2335                 code = FLEX_CODE;
2336                 string s = cmd.getArg(0);
2337                 InsetLayout il =
2338                         cur.buffer()->params().documentClass().insetLayout(from_utf8(s));
2339                 if (il.lyxtype() != InsetLayout::CHARSTYLE &&
2340                     il.lyxtype() != InsetLayout::CUSTOM &&
2341                     il.lyxtype() != InsetLayout::ELEMENT &&
2342                     il.lyxtype ()!= InsetLayout::STANDARD)
2343                         enable = false;
2344                 break;
2345                 }
2346         case LFUN_BOX_INSERT:
2347                 code = BOX_CODE;
2348                 break;
2349         case LFUN_BRANCH_INSERT:
2350                 code = BRANCH_CODE;
2351                 if (cur.buffer()->masterBuffer()->params().branchlist().empty()
2352                     && cur.buffer()->params().branchlist().empty())
2353                         enable = false;
2354                 break;
2355         case LFUN_PHANTOM_INSERT:
2356                 code = PHANTOM_CODE;
2357                 break;
2358         case LFUN_LABEL_INSERT:
2359                 code = LABEL_CODE;
2360                 break;
2361         case LFUN_LINE_INSERT:
2362                 code = LINE_CODE;
2363                 break;
2364         case LFUN_INFO_INSERT:
2365                 code = INFO_CODE;
2366                 break;
2367         case LFUN_OPTIONAL_INSERT:
2368                 code = OPTARG_CODE;
2369                 enable = cur.paragraph().insetList().count(OPTARG_CODE)
2370                         < cur.paragraph().layout().optionalargs;
2371                 break;
2372         case LFUN_INDEX_INSERT:
2373                 code = INDEX_CODE;
2374                 break;
2375         case LFUN_INDEX_PRINT:
2376                 code = INDEX_PRINT_CODE;
2377                 // not allowed in description items
2378                 enable = !inDescriptionItem(cur);
2379                 break;
2380         case LFUN_NOMENCL_INSERT:
2381                 if (cur.selIsMultiCell() || cur.selIsMultiLine()) {
2382                         enable = false;
2383                         break;
2384                 }
2385                 code = NOMENCL_CODE;
2386                 break;
2387         case LFUN_NOMENCL_PRINT:
2388                 code = NOMENCL_PRINT_CODE;
2389                 // not allowed in description items
2390                 enable = !inDescriptionItem(cur);
2391                 break;
2392         case LFUN_TOC_INSERT:
2393                 code = TOC_CODE;
2394                 // not allowed in description items
2395                 enable = !inDescriptionItem(cur);
2396                 break;
2397         case LFUN_HYPERLINK_INSERT:
2398                 if (cur.selIsMultiCell() || cur.selIsMultiLine()) {
2399                         enable = false;
2400                         break;
2401                 }
2402                 code = HYPERLINK_CODE;
2403                 break;
2404         case LFUN_QUOTE_INSERT:
2405                 // always allow this, since we will inset a raw quote
2406                 // if an inset is not allowed.
2407                 break;
2408         case LFUN_SPECIALCHAR_INSERT:
2409                 code = SPECIALCHAR_CODE;
2410                 break;
2411         case LFUN_SPACE_INSERT:
2412                 // slight hack: we know this is allowed in math mode
2413                 if (cur.inTexted())
2414                         code = SPACE_CODE;
2415                 break;
2416
2417         case LFUN_MATH_INSERT:
2418         case LFUN_MATH_AMS_MATRIX:
2419         case LFUN_MATH_MATRIX:
2420         case LFUN_MATH_DELIM:
2421         case LFUN_MATH_BIGDELIM:
2422         case LFUN_MATH_DISPLAY:
2423         case LFUN_MATH_MODE:
2424         case LFUN_MATH_MACRO:
2425         case LFUN_MATH_SUBSCRIPT:
2426         case LFUN_MATH_SUPERSCRIPT:
2427                 code = MATH_HULL_CODE;
2428                 break;
2429
2430         case LFUN_INSET_MODIFY:
2431                 // We need to disable this, because we may get called for a
2432                 // tabular cell via
2433                 // InsetTabular::getStatus() -> InsetText::getStatus()
2434                 // and we don't handle LFUN_INSET_MODIFY.
2435                 enable = false;
2436                 break;
2437
2438         case LFUN_FONT_EMPH:
2439                 flag.setOnOff(fontinfo.emph() == FONT_ON);
2440                 break;
2441
2442         case LFUN_FONT_ITAL:
2443                 flag.setOnOff(fontinfo.shape() == ITALIC_SHAPE);
2444                 break;
2445
2446         case LFUN_FONT_NOUN:
2447                 flag.setOnOff(fontinfo.noun() == FONT_ON);
2448                 break;
2449
2450         case LFUN_FONT_BOLD:
2451         case LFUN_FONT_BOLDSYMBOL:
2452                 flag.setOnOff(fontinfo.series() == BOLD_SERIES);
2453                 break;
2454
2455         case LFUN_FONT_SANS:
2456                 flag.setOnOff(fontinfo.family() == SANS_FAMILY);
2457                 break;
2458
2459         case LFUN_FONT_ROMAN:
2460                 flag.setOnOff(fontinfo.family() == ROMAN_FAMILY);
2461                 break;
2462
2463         case LFUN_FONT_TYPEWRITER:
2464                 flag.setOnOff(fontinfo.family() == TYPEWRITER_FAMILY);
2465                 break;
2466
2467         case LFUN_CUT:
2468         case LFUN_COPY:
2469                 enable = cur.selection();
2470                 break;
2471
2472         case LFUN_PASTE: {
2473                 if (cmd.argument().empty()) {
2474                         if (theClipboard().isInternal())
2475                                 enable = cap::numberOfSelections() > 0;
2476                         else
2477                                 enable = !theClipboard().empty();
2478                         break;
2479                 }
2480
2481                 // we have an argument
2482                 string const arg = to_utf8(cmd.argument());
2483                 if (isStrUnsignedInt(arg)) {
2484                         // it's a number and therefore means the internal stack
2485                         unsigned int n = convert<unsigned int>(arg);
2486                         enable = cap::numberOfSelections() > n;
2487                         break;
2488                 }
2489
2490                 // explicit graphics type?
2491                 Clipboard::GraphicsType type = Clipboard::AnyGraphicsType;
2492                 if ((arg == "pdf" && (type = Clipboard::PdfGraphicsType))
2493                           || (arg == "png" && (type = Clipboard::PngGraphicsType))
2494                           || (arg == "jpeg" && (type = Clipboard::JpegGraphicsType))
2495                           || (arg == "linkback" &&  (type = Clipboard::LinkBackGraphicsType))
2496                           || (arg == "emf" &&  (type = Clipboard::EmfGraphicsType))
2497                           || (arg == "wmf" &&  (type = Clipboard::WmfGraphicsType))) {
2498                         enable = theClipboard().hasGraphicsContents(type);
2499                         break;
2500                 }
2501
2502                 // unknown argument
2503                 enable = false;
2504                 break;
2505          }
2506
2507         case LFUN_CLIPBOARD_PASTE:
2508                 enable = !theClipboard().empty();
2509                 break;
2510
2511         case LFUN_PRIMARY_SELECTION_PASTE:
2512                 enable = cur.selection() || !theSelection().empty();
2513                 break;
2514
2515         case LFUN_SELECTION_PASTE:
2516                 enable = cap::selection();
2517                 break;
2518
2519         case LFUN_PARAGRAPH_MOVE_UP:
2520                 enable = cur.pit() > 0 && !cur.selection();
2521                 break;
2522
2523         case LFUN_PARAGRAPH_MOVE_DOWN:
2524                 enable = cur.pit() < cur.lastpit() && !cur.selection();
2525                 break;
2526
2527         case LFUN_INSET_DISSOLVE:
2528                 if (!cmd.argument().empty()) {
2529                         InsetLayout const & il = cur.inset().getLayout();
2530                         InsetLayout::InsetLyXType const type = 
2531                                         translateLyXType(to_utf8(cmd.argument()));
2532                         enable = cur.inset().lyxCode() == FLEX_CODE
2533                                  && il.lyxtype() == type;
2534                 } else {
2535                         enable = ((!isMainText()
2536                                       && cur.inset().nargs() == 1)
2537                                   || (cur.nextInset()
2538                                       && cur.nextInset()->nargs() == 1));
2539                 }
2540                 break;
2541
2542         case LFUN_CHANGE_ACCEPT:
2543         case LFUN_CHANGE_REJECT:
2544                 // In principle, these LFUNs should only be enabled if there
2545                 // is a change at the current position/in the current selection.
2546                 // However, without proper optimizations, this will inevitably
2547                 // result in unacceptable performance - just imagine a user who
2548                 // wants to select the complete content of a long document.
2549                 if (!cur.selection())
2550                         enable = cur.paragraph().isChanged(cur.pos());
2551                 else
2552                         // TODO: context-sensitive enabling of LFUN_CHANGE_ACCEPT/REJECT
2553                         // for selections.
2554                         enable = true;
2555                 break;
2556
2557         case LFUN_OUTLINE_UP:
2558         case LFUN_OUTLINE_DOWN:
2559         case LFUN_OUTLINE_IN:
2560         case LFUN_OUTLINE_OUT:
2561         case LFUN_OUTLINE_DRAGMOVE:
2562                 // FIXME: LyX is not ready for outlining within inset.
2563                 enable = isMainText()
2564                         && cur.paragraph().layout().toclevel != Layout::NOT_IN_TOC;
2565                 break;
2566
2567         case LFUN_NEWLINE_INSERT:
2568                 // LaTeX restrictions (labels or empty par)
2569                 enable = (cur.pos() > cur.paragraph().beginOfBody());
2570                 break;
2571
2572         case LFUN_TAB_INSERT:
2573         case LFUN_TAB_DELETE:
2574                 enable = cur.inset().getLayout().isPassThru();
2575                 break;
2576
2577         case LFUN_SET_GRAPHICS_GROUP: {
2578                 InsetGraphics * ins = graphics::getCurrentGraphicsInset(cur);
2579                 if (!ins)
2580                         enable = false;
2581                 else
2582                         flag.setOnOff(to_utf8(cmd.argument()) == ins->getParams().groupId);
2583                 break;
2584         }
2585
2586         case LFUN_NEWPAGE_INSERT:
2587                 // not allowed in description items
2588                 code = NEWPAGE_CODE;
2589                 enable = !inDescriptionItem(cur);
2590                 break;
2591
2592         case LFUN_DATE_INSERT: {
2593                 string const format = cmd.argument().empty()
2594                         ? lyxrc.date_insert_format : to_utf8(cmd.argument());
2595                 enable = support::os::is_valid_strftime(format);
2596                 break;
2597         }
2598
2599         case LFUN_LANGUAGE:
2600                 enable = !cur.inset().getLayout().isPassThru();
2601
2602         case LFUN_BREAK_PARAGRAPH:
2603                 enable = cur.inset().getLayout().isMultiPar();
2604
2605         case LFUN_WORD_DELETE_FORWARD:
2606         case LFUN_WORD_DELETE_BACKWARD:
2607         case LFUN_LINE_DELETE:
2608         case LFUN_WORD_FORWARD:
2609         case LFUN_WORD_BACKWARD:
2610         case LFUN_WORD_RIGHT:
2611         case LFUN_WORD_LEFT:
2612         case LFUN_CHAR_FORWARD:
2613         case LFUN_CHAR_FORWARD_SELECT:
2614         case LFUN_CHAR_BACKWARD:
2615         case LFUN_CHAR_BACKWARD_SELECT:
2616         case LFUN_CHAR_LEFT:
2617         case LFUN_CHAR_LEFT_SELECT:
2618         case LFUN_CHAR_RIGHT:
2619         case LFUN_CHAR_RIGHT_SELECT:
2620         case LFUN_UP:
2621         case LFUN_UP_SELECT:
2622         case LFUN_DOWN:
2623         case LFUN_DOWN_SELECT:
2624         case LFUN_PARAGRAPH_UP_SELECT:
2625         case LFUN_PARAGRAPH_DOWN_SELECT:
2626         case LFUN_LINE_BEGIN_SELECT:
2627         case LFUN_LINE_END_SELECT:
2628         case LFUN_WORD_FORWARD_SELECT:
2629         case LFUN_WORD_BACKWARD_SELECT:
2630         case LFUN_WORD_RIGHT_SELECT:
2631         case LFUN_WORD_LEFT_SELECT:
2632         case LFUN_WORD_SELECT:
2633         case LFUN_SECTION_SELECT:
2634         case LFUN_PARAGRAPH_UP:
2635         case LFUN_PARAGRAPH_DOWN:
2636         case LFUN_LINE_BEGIN:
2637         case LFUN_LINE_END:
2638         case LFUN_CHAR_DELETE_FORWARD:
2639         case LFUN_CHAR_DELETE_BACKWARD:
2640         case LFUN_INSET_INSERT:
2641         case LFUN_WORD_UPCASE:
2642         case LFUN_WORD_LOWCASE:
2643         case LFUN_WORD_CAPITALIZE:
2644         case LFUN_CHARS_TRANSPOSE:
2645         case LFUN_SERVER_GET_XY:
2646         case LFUN_SERVER_SET_XY:
2647         case LFUN_SERVER_GET_LAYOUT:
2648         case LFUN_LAYOUT:
2649         case LFUN_SELF_INSERT:
2650         case LFUN_FONT_DEFAULT:
2651         case LFUN_FONT_UNDERLINE:
2652         case LFUN_FONT_STRIKEOUT:
2653         case LFUN_FONT_UULINE:
2654         case LFUN_FONT_UWAVE:
2655         case LFUN_FONT_SIZE:
2656         case LFUN_TEXTSTYLE_APPLY:
2657         case LFUN_TEXTSTYLE_UPDATE:
2658         case LFUN_LAYOUT_PARAGRAPH:
2659         case LFUN_PARAGRAPH_UPDATE:
2660         case LFUN_ACCENT_UMLAUT:
2661         case LFUN_ACCENT_CIRCUMFLEX:
2662         case LFUN_ACCENT_GRAVE:
2663         case LFUN_ACCENT_ACUTE:
2664         case LFUN_ACCENT_TILDE:
2665         case LFUN_ACCENT_CEDILLA:
2666         case LFUN_ACCENT_MACRON:
2667         case LFUN_ACCENT_DOT:
2668         case LFUN_ACCENT_UNDERDOT:
2669         case LFUN_ACCENT_UNDERBAR:
2670         case LFUN_ACCENT_CARON:
2671         case LFUN_ACCENT_BREVE:
2672         case LFUN_ACCENT_TIE:
2673         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
2674         case LFUN_ACCENT_CIRCLE:
2675         case LFUN_ACCENT_OGONEK:
2676         case LFUN_THESAURUS_ENTRY:
2677         case LFUN_PARAGRAPH_PARAMS_APPLY:
2678         case LFUN_PARAGRAPH_PARAMS:
2679         case LFUN_ESCAPE:
2680         case LFUN_BUFFER_BEGIN:
2681         case LFUN_BUFFER_END:
2682         case LFUN_BUFFER_BEGIN_SELECT:
2683         case LFUN_BUFFER_END_SELECT:
2684         case LFUN_INSET_BEGIN:
2685         case LFUN_INSET_END:
2686         case LFUN_INSET_BEGIN_SELECT:
2687         case LFUN_INSET_END_SELECT:
2688         case LFUN_INSET_SELECT_ALL:
2689         case LFUN_UNICODE_INSERT:
2690                 // these are handled in our dispatch()
2691                 enable = true;
2692                 break;
2693
2694         default:
2695                 return false;
2696         }
2697
2698         if (code != NO_CODE
2699             && (cur.empty() 
2700                 || !cur.inset().insetAllowed(code)
2701                 || cur.paragraph().layout().pass_thru))
2702                 enable = false;
2703
2704         switch (cmd.action) {
2705         case LFUN_ACCENT_ACUTE:
2706         case LFUN_ACCENT_BREVE:
2707         case LFUN_ACCENT_CARON:
2708         case LFUN_ACCENT_CEDILLA:
2709         case LFUN_ACCENT_CIRCLE:
2710         case LFUN_ACCENT_CIRCUMFLEX:
2711         case LFUN_ACCENT_DOT:
2712         case LFUN_ACCENT_GRAVE:
2713         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
2714         case LFUN_ACCENT_MACRON:
2715         case LFUN_ACCENT_OGONEK:
2716         case LFUN_ACCENT_TIE:
2717         case LFUN_ACCENT_TILDE:
2718         case LFUN_ACCENT_UMLAUT:
2719         case LFUN_ACCENT_UNDERBAR:
2720         case LFUN_ACCENT_UNDERDOT:
2721         case LFUN_APPENDIX:
2722         case LFUN_DEPTH_DECREMENT:
2723         case LFUN_DEPTH_INCREMENT:
2724         case LFUN_FILE_INSERT:
2725         case LFUN_FONT_BOLD:
2726         case LFUN_FONT_BOLDSYMBOL:
2727         case LFUN_FONT_TYPEWRITER:
2728         case LFUN_FONT_DEFAULT:
2729         case LFUN_FONT_EMPH:
2730         case LFUN_FONT_NOUN:
2731         case LFUN_FONT_ROMAN:
2732         case LFUN_FONT_SANS:
2733         case LFUN_FONT_FRAK:
2734         case LFUN_FONT_ITAL:
2735         case LFUN_FONT_SIZE:
2736         case LFUN_FONT_STATE:
2737         case LFUN_FONT_UNDERLINE:
2738         case LFUN_FONT_STRIKEOUT:
2739         case LFUN_FONT_UULINE:
2740         case LFUN_FONT_UWAVE:
2741         case LFUN_LABEL_GOTO:
2742         case LFUN_LAYOUT_TABULAR:
2743         case LFUN_MENU_OPEN:
2744         case LFUN_NOACTION:
2745         case LFUN_NOTE_NEXT:
2746         case LFUN_REFERENCE_NEXT:
2747         case LFUN_SERVER_GOTO_FILE_ROW:
2748         case LFUN_SERVER_NOTIFY:
2749         case LFUN_SERVER_SET_XY:
2750         case LFUN_TEXTSTYLE_APPLY:
2751         case LFUN_TEXTSTYLE_UPDATE:
2752                 if (cur.inset().getLayout().isPassThru())
2753                         enable = false;
2754                 break;
2755         default:
2756                 break;
2757         }
2758
2759         flag.setEnabled(enable);
2760         return true;
2761 }
2762
2763
2764 void Text::pasteString(Cursor & cur, docstring const & clip,
2765                 bool asParagraphs)
2766 {
2767         cur.clearSelection();
2768         if (!clip.empty()) {
2769                 cur.recordUndo();
2770                 if (asParagraphs)
2771                         insertStringAsParagraphs(cur, clip, cur.current_font);
2772                 else
2773                         insertStringAsLines(cur, clip, cur.current_font);
2774         }
2775 }
2776
2777
2778 // FIXME: an item inset would make things much easier.
2779 bool Text::inDescriptionItem(Cursor & cur) const
2780 {
2781         Paragraph & par = cur.paragraph();
2782         pos_type const pos = cur.pos();
2783         pos_type const body_pos = par.beginOfBody();
2784
2785         if (par.layout().latextype != LATEX_LIST_ENVIRONMENT
2786             && (par.layout().latextype != LATEX_ITEM_ENVIRONMENT
2787                 || par.layout().margintype != MARGIN_FIRST_DYNAMIC))
2788                 return false;
2789
2790         return (pos < body_pos
2791                 || (pos == body_pos
2792                     && (pos == 0 || par.getChar(pos - 1) != ' ')));
2793 }
2794
2795 } // namespace lyx