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