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