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