]> git.lyx.org Git - lyx.git/blob - src/Text3.cpp
support for \linebreak:
[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 "Cursor.h"
29 #include "CutAndPaste.h"
30 #include "debug.h"
31 #include "DispatchResult.h"
32 #include "ErrorList.h"
33 #include "factory.h"
34 #include "FuncRequest.h"
35 #include "gettext.h"
36 #include "InsetList.h"
37 #include "Intl.h"
38 #include "Language.h"
39 #include "Layout.h"
40 #include "LyXAction.h"
41 #include "LyXFunc.h"
42 #include "Lexer.h"
43 #include "LyXRC.h"
44 #include "Paragraph.h"
45 #include "paragraph_funcs.h"
46 #include "ParagraphParameters.h"
47 #include "ParIterator.h"
48 #include "TextClass.h"
49 #include "TextMetrics.h"
50 #include "VSpace.h"
51
52 #include "frontends/Clipboard.h"
53 #include "frontends/Selection.h"
54
55 #include "insets/InsetCollapsable.h"
56 #include "insets/InsetCommand.h"
57 #include "insets/InsetFloatList.h"
58 #include "insets/InsetNewline.h"
59 #include "insets/InsetQuotes.h"
60 #include "insets/InsetSpecialChar.h"
61 #include "insets/InsetText.h"
62 #include "insets/InsetInfo.h"
63
64 #include "support/lstrings.h"
65 #include "support/lyxlib.h"
66 #include "support/convert.h"
67 #include "support/lyxtime.h"
68
69 #include "mathed/InsetMathHull.h"
70 #include "mathed/MathMacroTemplate.h"
71
72 #include <boost/current_function.hpp>
73 #include <boost/next_prior.hpp>
74
75 #include <clocale>
76 #include <sstream>
77
78 using std::endl;
79 using std::string;
80 using std::istringstream;
81 using std::ostringstream;
82
83 namespace lyx {
84
85 using cap::copySelection;
86 using cap::cutSelection;
87 using cap::pasteFromStack;
88 using cap::pasteClipboard;
89 using cap::replaceSelection;
90
91 using support::isStrUnsignedInt;
92 using support::token;
93
94 // globals...
95 static Font freefont(ignore_font, ignore_language);
96 static bool toggleall = false;
97
98 static void toggleAndShow(Cursor & cur, Text * text,
99         Font const & font, bool toggleall = true)
100 {
101         text->toggleFree(cur, font, toggleall);
102
103         if (font.language() != ignore_language ||
104             font.fontInfo().number() != FONT_IGNORE) {
105                 TextMetrics const & tm = cur.bv().textMetrics(text);
106                 if (cur.boundary() != tm.isRTLBoundary(cur.pit(), cur.pos(),
107                                                        cur.real_current_font))
108                         text->setCursor(cur, cur.pit(), cur.pos(),
109                                         false, !cur.boundary());
110         }
111 }
112
113
114 static void moveCursor(Cursor & cur, bool selecting)
115 {
116         if (selecting || cur.mark())
117                 cur.setSelection();
118 }
119
120
121 static void finishChange(Cursor & cur, bool selecting)
122 {
123         cur.finishUndo();
124         moveCursor(cur, selecting);
125 }
126
127
128 static void mathDispatch(Cursor & cur, FuncRequest const & cmd, bool display)
129 {
130         cur.recordUndo();
131         docstring sel = cur.selectionAsString(false);
132
133         // It may happen that sel is empty but there is a selection
134         replaceSelection(cur);
135
136         if (sel.empty()) {
137 #ifdef ENABLE_ASSERTIONS
138                 const int old_pos = cur.pos();
139 #endif
140                 cur.insert(new InsetMathHull(hullSimple));
141                 BOOST_ASSERT(old_pos == cur.pos());
142                 cur.nextInset()->edit(cur, true);
143                 // don't do that also for LFUN_MATH_MODE
144                 // unless you want end up with always changing
145                 // to mathrm when opening an inlined inset --
146                 // I really hate "LyXfunc overloading"...
147                 if (display)
148                         cur.dispatch(FuncRequest(LFUN_MATH_DISPLAY));
149                 // Avoid an unnecessary undo step if cmd.argument
150                 // is empty
151                 if (!cmd.argument().empty())
152                         cur.dispatch(FuncRequest(LFUN_MATH_INSERT,
153                                                  cmd.argument()));
154         } else {
155                 // create a macro if we see "\\newcommand"
156                 // somewhere, and an ordinary formula
157                 // otherwise
158                 if (sel.find(from_ascii("\\newcommand")) == string::npos
159                                 && sel.find(from_ascii("\\def")) == string::npos)
160                 {
161                         InsetMathHull * formula = new InsetMathHull;
162                         istringstream is(to_utf8(sel));
163                         Lexer lex(0, 0);
164                         lex.setStream(is);
165                         formula->read(cur.buffer(), lex);
166                         if (formula->getType() == hullNone)
167                                 // Don't create pseudo formulas if
168                                 // delimiters are left out
169                                 formula->mutate(hullSimple);
170                         cur.insert(formula);
171                 } else {
172                         cur.insert(new MathMacroTemplate(sel));
173                 }
174         }
175         cur.message(from_utf8(N_("Math editor mode")));
176 }
177
178
179 static void specialChar(Cursor & cur, InsetSpecialChar::Kind kind)
180 {
181         cur.recordUndo();
182         cap::replaceSelection(cur);
183         cur.insert(new InsetSpecialChar(kind));
184         cur.posForward();
185 }
186
187
188 static bool doInsertInset(Cursor & cur, Text * text,
189         FuncRequest const & cmd, bool edit, bool pastesel)
190 {
191         Inset * inset = createInset(cur.bv().buffer(), cmd);
192         if (!inset)
193                 return false;
194
195         if (InsetCollapsable * ci = inset->asInsetCollapsable())
196                 ci->setLayout(cur.bv().buffer().params());
197
198         cur.recordUndo();
199         if (cmd.action == LFUN_INDEX_INSERT) {
200                 docstring ds = support::subst(text->getStringToIndex(cur), '\n', ' ');
201                 text->insertInset(cur, inset);
202                 if (edit)
203                         inset->edit(cur, true);
204                 // Now put this into inset
205                 static_cast<InsetCollapsable *>(inset)->text_.insertStringAsParagraphs(cur, ds);
206         } else {
207                 bool gotsel = false;
208                 if (cur.selection()) {
209                         lyx::dispatch(FuncRequest(LFUN_CUT));
210                         gotsel = true;
211                 }
212                 text->insertInset(cur, inset);
213
214                 if (edit)
215                         inset->edit(cur, true);
216
217                 if (gotsel && pastesel) {
218                         lyx::dispatch(FuncRequest(LFUN_PASTE, "0"));
219                         InsetText * insetText = dynamic_cast<InsetText *>(inset);
220                         if (insetText && !insetText->allowMultiPar() 
221                             || cur.lastpit() == 0) {
222                                 // reset first par to default
223                                 LayoutPtr const layout =
224                                         cur.buffer().params().getTextClass().defaultLayout();
225                                 cur.text()->paragraphs().begin()->layout(layout);
226                                 cur.pos() = 0;
227                                 cur.pit() = 0;
228                                 // Merge multiple paragraphs -- hack
229                                 while (cur.lastpit() > 0) {
230                                         mergeParagraph(cur.buffer().params(),
231                                                 cur.text()->paragraphs(), 0);
232                                 }
233                         } else {
234                                 // reset surrounding par to default
235                                 docstring const layoutname = 
236                                         cur.buffer().params().getTextClass().defaultLayoutName();
237                                 cur.leaveInset(*inset);
238                                 text->setLayout(cur, layoutname);
239                         }
240                 }
241         }
242         return true;
243 }
244
245
246 string const freefont2string()
247 {
248         return freefont.toString(toggleall);
249 }
250
251
252 /// the type of outline operation
253 enum OutlineOp {
254         OutlineUp, // Move this header with text down
255         OutlineDown,   // Move this header with text up
256         OutlineIn, // Make this header deeper
257         OutlineOut // Make this header shallower
258 };
259
260
261 static void outline(OutlineOp mode, Cursor & cur)
262 {
263         Buffer & buf = cur.buffer();
264         pit_type & pit = cur.pit();
265         ParagraphList & pars = buf.text().paragraphs();
266         ParagraphList::iterator bgn = pars.begin();
267         // The first paragraph of the area to be copied:
268         ParagraphList::iterator start = boost::next(bgn, pit);
269         // The final paragraph of area to be copied:
270         ParagraphList::iterator finish = start;
271         ParagraphList::iterator end = pars.end();
272
273         TextClass::const_iterator lit =
274                 buf.params().getTextClass().begin();
275         TextClass::const_iterator const lend =
276                 buf.params().getTextClass().end();
277
278         int const thistoclevel = start->layout()->toclevel;
279         int toclevel;
280         switch (mode) {
281                 case OutlineUp: {
282                         // Move out (down) from this section header
283                         if (finish != end)
284                                 ++finish;
285                         // Seek the one (on same level) below
286                         for (; finish != end; ++finish) {
287                                 toclevel = finish->layout()->toclevel;
288                                 if (toclevel != Layout::NOT_IN_TOC
289                                     && toclevel <= thistoclevel) {
290                                         break;
291                                 }
292                         }
293                         ParagraphList::iterator dest = start;
294                         // Move out (up) from this header
295                         if (dest == bgn)
296                                 break;
297                         // Search previous same-level header above
298                         do {
299                                 --dest;
300                                 toclevel = dest->layout()->toclevel;
301                         } while(dest != bgn
302                                 && (toclevel == Layout::NOT_IN_TOC
303                                     || toclevel > thistoclevel));
304                         // Not found; do nothing
305                         if (toclevel == Layout::NOT_IN_TOC || toclevel > thistoclevel)
306                                 break;
307                         pit_type const newpit = std::distance(bgn, dest);
308                         pit_type const len = std::distance(start, finish);
309                         pit_type const deletepit = pit + len;
310                         buf.undo().recordUndo(cur, ATOMIC_UNDO, newpit, deletepit - 1);
311                         pars.insert(dest, start, finish);
312                         start = boost::next(pars.begin(), deletepit);
313                         pit = newpit;
314                         pars.erase(start, finish);
315                         break;
316                 }
317                 case OutlineDown: {
318                         // Go down out of current header:
319                         if (finish != end)
320                                 ++finish;
321                         // Find next same-level header:
322                         for (; finish != end; ++finish) {
323                                 toclevel = finish->layout()->toclevel;
324                                 if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel)
325                                         break;
326                         }
327                         ParagraphList::iterator dest = finish;
328                         // Go one down from *this* header:
329                         if (dest != end)
330                                 ++dest;
331                         else
332                                 break;
333                         // Go further down to find header to insert in front of:
334                         for (; dest != end; ++dest) {
335                                 toclevel = dest->layout()->toclevel;
336                                 if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel)
337                                         break;
338                         }
339                         // One such was found:
340                         pit_type newpit = std::distance(bgn, dest);
341                         pit_type const len = std::distance(start, finish);
342                         buf.undo().recordUndo(cur, ATOMIC_UNDO, pit, newpit - 1);
343                         pars.insert(dest, start, finish);
344                         start = boost::next(bgn, pit);
345                         pit = newpit - len;
346                         pars.erase(start, finish);
347                         break;
348                 }
349                 case OutlineIn:
350                         buf.undo().recordUndo(cur);
351                         for (; lit != lend; ++lit) {
352                                 if ((*lit)->toclevel == thistoclevel + 1 &&
353                                     start->layout()->labeltype == (*lit)->labeltype) {
354                                         start->layout((*lit));
355                                         break;
356                                 }
357                         }
358                         break;
359                 case OutlineOut:
360                         buf.undo().recordUndo(cur);
361                         for (; lit != lend; ++lit) {
362                                 if ((*lit)->toclevel == thistoclevel - 1 &&
363                                     start->layout()->labeltype == (*lit)->labeltype) {
364                                         start->layout((*lit));
365                                         break;
366                                 }
367                         }
368                         break;
369                 default:
370                         break;
371         }
372 }
373
374
375 void Text::number(Cursor & cur)
376 {
377         FontInfo font = ignore_font;
378         font.setNumber(FONT_TOGGLE);
379         toggleAndShow(cur, this, Font(font));
380 }
381
382
383 bool Text::isRTL(Buffer const & buffer, Paragraph const & par) const
384 {
385         return par.isRTL(buffer.params());
386 }
387
388
389 void Text::dispatch(Cursor & cur, FuncRequest & cmd)
390 {
391         LYXERR(Debug::ACTION, "Text::dispatch: cmd: " << cmd);
392
393         // FIXME: We use the update flag to indicates wether a singlePar or a
394         // full screen update is needed. We reset it here but shall we restore it
395         // at the end?
396         cur.noUpdate();
397
398         BOOST_ASSERT(cur.text() == this);
399         BufferView * bv = &cur.bv();
400         TextMetrics & tm = cur.bv().textMetrics(this);
401         CursorSlice oldTopSlice = cur.top();
402         bool oldBoundary = cur.boundary();
403         bool sel = cur.selection();
404         // Signals that, even if needsUpdate == false, an update of the
405         // cursor paragraph is required
406         bool singleParUpdate = lyxaction.funcHasFlag(cmd.action,
407                 LyXAction::SingleParUpdate);
408         // Signals that a full-screen update is required
409         bool needsUpdate = !(lyxaction.funcHasFlag(cmd.action,
410                 LyXAction::NoUpdate) || singleParUpdate);
411         // Remember the old paragraph metric (_outer_ paragraph!)
412         ParagraphMetrics const & pm = cur.bv().parMetrics(
413                 cur.bottom().text(), cur.bottom().pit());
414         Dimension olddim = pm.dim();
415
416         switch (cmd.action) {
417
418         case LFUN_PARAGRAPH_MOVE_DOWN: {
419                 pit_type const pit = cur.pit();
420                 recUndo(cur, pit, pit + 1);
421                 cur.finishUndo();
422                 std::swap(pars_[pit], pars_[pit + 1]);
423                 updateLabels(cur.buffer());
424                 needsUpdate = true;
425                 ++cur.pit();
426                 break;
427         }
428
429         case LFUN_PARAGRAPH_MOVE_UP: {
430                 pit_type const pit = cur.pit();
431                 recUndo(cur, pit - 1, pit);
432                 cur.finishUndo();
433                 std::swap(pars_[pit], pars_[pit - 1]);
434                 updateLabels(cur.buffer());
435                 --cur.pit();
436                 needsUpdate = true;
437                 break;
438         }
439
440         case LFUN_APPENDIX: {
441                 Paragraph & par = cur.paragraph();
442                 bool start = !par.params().startOfAppendix();
443
444 // FIXME: The code below only makes sense at top level.
445 // Should LFUN_APPENDIX be restricted to top-level paragraphs?
446                 // ensure that we have only one start_of_appendix in this document
447                 // FIXME: this don't work for multipart document!
448                 for (pit_type tmp = 0, end = pars_.size(); tmp != end; ++tmp) {
449                         if (pars_[tmp].params().startOfAppendix()) {
450                                 recUndo(cur, tmp);
451                                 pars_[tmp].params().startOfAppendix(false);
452                                 break;
453                         }
454                 }
455
456                 cur.recordUndo();
457                 par.params().startOfAppendix(start);
458
459                 // we can set the refreshing parameters now
460                 updateLabels(cur.buffer());
461                 break;
462         }
463
464         case LFUN_WORD_DELETE_FORWARD:
465                 if (cur.selection()) {
466                         cutSelection(cur, true, false);
467                 } else
468                         deleteWordForward(cur);
469                 finishChange(cur, false);
470                 break;
471
472         case LFUN_WORD_DELETE_BACKWARD:
473                 if (cur.selection()) {
474                         cutSelection(cur, true, false);
475                 } else
476                         deleteWordBackward(cur);
477                 finishChange(cur, false);
478                 break;
479
480         case LFUN_LINE_DELETE:
481                 if (cur.selection()) {
482                         cutSelection(cur, true, false);
483                 } else
484                         tm.deleteLineForward(cur);
485                 finishChange(cur, false);
486                 break;
487
488         case LFUN_BUFFER_BEGIN:
489         case LFUN_BUFFER_BEGIN_SELECT:
490                 needsUpdate |= cur.selHandle(cmd.action == LFUN_BUFFER_BEGIN_SELECT);
491                 if (cur.depth() == 1) {
492                         needsUpdate |= cursorTop(cur);
493                 } else {
494                         cur.undispatched();
495                 }
496                 break;
497
498         case LFUN_BUFFER_END:
499         case LFUN_BUFFER_END_SELECT:
500                 needsUpdate |= cur.selHandle(cmd.action == LFUN_BUFFER_END_SELECT);
501                 if (cur.depth() == 1) {
502                         needsUpdate |= cursorBottom(cur);
503                 } else {
504                         cur.undispatched();
505                 }
506                 break;
507
508         case LFUN_CHAR_FORWARD:
509         case LFUN_CHAR_FORWARD_SELECT:
510                 //lyxerr << BOOST_CURRENT_FUNCTION
511                 //       << " LFUN_CHAR_FORWARD[SEL]:\n" << cur << endl;
512                 needsUpdate |= cur.selHandle(cmd.action == LFUN_CHAR_FORWARD_SELECT);
513                 needsUpdate |= cursorForward(cur);
514
515                 if (!needsUpdate && oldTopSlice == cur.top()
516                                 && cur.boundary() == oldBoundary) {
517                         cur.undispatched();
518                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
519                 }
520                 break;
521
522         case LFUN_CHAR_BACKWARD:
523         case LFUN_CHAR_BACKWARD_SELECT:
524                 //lyxerr << "handle LFUN_CHAR_BACKWARD[_SELECT]:\n" << cur << endl;
525                 needsUpdate |= cur.selHandle(cmd.action == LFUN_CHAR_BACKWARD_SELECT);
526                 needsUpdate |= cursorBackward(cur);
527
528                 if (!needsUpdate && oldTopSlice == cur.top()
529                         && cur.boundary() == oldBoundary) {
530                         cur.undispatched();
531                         cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
532                 }
533                 break;
534
535         case LFUN_CHAR_LEFT:
536         case LFUN_CHAR_LEFT_SELECT:
537                 //FIXME: for visual cursor, really move left
538                 if (reverseDirectionNeeded(cur)) {
539                         cmd.action = cmd.action == LFUN_CHAR_LEFT_SELECT ? 
540                                         LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD;
541                 } else {
542                         cmd.action = cmd.action == LFUN_CHAR_LEFT_SELECT ? 
543                                         LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD;
544                 }
545                 dispatch(cur, cmd);
546                 return;
547
548         case LFUN_CHAR_RIGHT:
549         case LFUN_CHAR_RIGHT_SELECT:
550                 //FIXME: for visual cursor, really move right
551                 if (reverseDirectionNeeded(cur)) {
552                         cmd.action = cmd.action == LFUN_CHAR_RIGHT_SELECT ? 
553                                         LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD;
554                 } else {
555                         cmd.action = cmd.action == LFUN_CHAR_RIGHT_SELECT ? 
556                                         LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD;
557                 }
558                 dispatch(cur, cmd);
559                 return;
560
561         case LFUN_UP_SELECT:
562         case LFUN_DOWN_SELECT:
563         case LFUN_UP:
564         case LFUN_DOWN: {
565                 // stop/start the selection
566                 bool select = cmd.action == LFUN_DOWN_SELECT ||
567                         cmd.action == LFUN_UP_SELECT;
568                 cur.selHandle(select);
569                 
570                 // move cursor up/down
571                 bool up = cmd.action == LFUN_UP_SELECT || cmd.action == LFUN_UP;
572                 bool const successful = cur.upDownInText(up, needsUpdate);
573                 if (successful) {
574                         // notify insets which were left and get their update flags 
575                         notifyCursorLeaves(cur.beforeDispatchCursor(), cur);
576                         cur.fixIfBroken();
577                         
578                         // redraw if you leave mathed (for the decorations)
579                         needsUpdate |= cur.beforeDispatchCursor().inMathed();
580                 } else
581                         cur.undispatched();
582                 
583                 break;
584         }
585
586         case LFUN_PARAGRAPH_UP:
587         case LFUN_PARAGRAPH_UP_SELECT:
588                 needsUpdate |= cur.selHandle(cmd.action == LFUN_PARAGRAPH_UP_SELECT);
589                 needsUpdate |= cursorUpParagraph(cur);
590                 break;
591
592         case LFUN_PARAGRAPH_DOWN:
593         case LFUN_PARAGRAPH_DOWN_SELECT:
594                 needsUpdate |= cur.selHandle(cmd.action == LFUN_PARAGRAPH_DOWN_SELECT);
595                 needsUpdate |= cursorDownParagraph(cur);
596                 break;
597
598         case LFUN_SCREEN_UP_SELECT:
599                 needsUpdate |= cur.selHandle(true);
600                 if (cur.pit() == 0 && cur.textRow().pos() == 0)
601                         cur.undispatched();
602                 else {
603                         tm.cursorPrevious(cur);
604                 }
605                 break;
606
607         case LFUN_SCREEN_DOWN_SELECT:
608                 needsUpdate |= cur.selHandle(true);
609                 if (cur.pit() == cur.lastpit()
610                           && cur.textRow().endpos() == cur.lastpos())
611                         cur.undispatched();
612                 else {
613                         tm.cursorNext(cur);
614                 }
615                 break;
616
617         case LFUN_LINE_BEGIN:
618         case LFUN_LINE_BEGIN_SELECT:
619                 needsUpdate |= cur.selHandle(cmd.action == LFUN_LINE_BEGIN_SELECT);
620                 needsUpdate |= tm.cursorHome(cur);
621                 break;
622
623         case LFUN_LINE_END:
624         case LFUN_LINE_END_SELECT:
625                 needsUpdate |= cur.selHandle(cmd.action == LFUN_LINE_END_SELECT);
626                 needsUpdate |= tm.cursorEnd(cur);
627                 break;
628
629         case LFUN_WORD_RIGHT:
630         case LFUN_WORD_RIGHT_SELECT:
631                 //FIXME: for visual cursor mode, really move right
632                 if (reverseDirectionNeeded(cur)) {
633                         cmd.action = cmd.action == LFUN_WORD_RIGHT_SELECT ?
634                                         LFUN_WORD_BACKWARD_SELECT : LFUN_WORD_BACKWARD;
635                 } else {
636                         cmd.action = cmd.action == LFUN_WORD_RIGHT_SELECT ?
637                                         LFUN_WORD_FORWARD_SELECT : LFUN_WORD_FORWARD;
638                 }
639                 dispatch(cur, cmd);
640                 return;
641
642         case LFUN_WORD_FORWARD:
643         case LFUN_WORD_FORWARD_SELECT:
644                 needsUpdate |= cur.selHandle(cmd.action == LFUN_WORD_FORWARD_SELECT);
645                 needsUpdate |= cursorForwardOneWord(cur);
646                 break;
647
648         case LFUN_WORD_LEFT:
649         case LFUN_WORD_LEFT_SELECT:
650                 //FIXME: for visual cursor mode, really move left
651                 if (reverseDirectionNeeded(cur)) {
652                         cmd.action = cmd.action == LFUN_WORD_LEFT_SELECT ?
653                                         LFUN_WORD_FORWARD_SELECT : LFUN_WORD_FORWARD;
654                 } else {
655                         cmd.action = cmd.action == LFUN_WORD_LEFT_SELECT ?
656                                         LFUN_WORD_BACKWARD_SELECT : LFUN_WORD_BACKWARD;
657                 }
658                 dispatch(cur, cmd);
659                 return;
660
661         case LFUN_WORD_BACKWARD:
662         case LFUN_WORD_BACKWARD_SELECT:
663                 needsUpdate |= cur.selHandle(cmd.action == LFUN_WORD_BACKWARD_SELECT);
664                 needsUpdate |= cursorBackwardOneWord(cur);
665                 break;
666
667         case LFUN_WORD_SELECT: {
668                 selectWord(cur, WHOLE_WORD);
669                 finishChange(cur, true);
670                 break;
671         }
672
673         case LFUN_NEW_LINE: {
674                 // Not allowed by LaTeX (labels or empty par)
675                 if (cur.pos() > cur.paragraph().beginOfBody()) {
676                         // this avoids a double undo
677                         // FIXME: should not be needed, ideally
678                         if (!cur.selection())
679                                 cur.recordUndo();
680                         cap::replaceSelection(cur);
681                         cur.insert(new InsetNewline);
682                         cur.posForward();
683                         moveCursor(cur, false);
684                 }
685                 break;
686         }
687         
688         case LFUN_LINE_BREAK: {
689                 // Not allowed by LaTeX (labels or empty par)
690                 if (cur.pos() > cur.paragraph().beginOfBody()) {
691                         // this avoids a double undo
692                         // FIXME: should not be needed, ideally
693                         if (!cur.selection())
694                                 cur.recordUndo();
695                         cap::replaceSelection(cur);
696                         cur.insert(new InsetLinebreak);
697                         cur.posForward();
698                         moveCursor(cur, false);
699                 }
700                 break;
701         }
702
703         case LFUN_CHAR_DELETE_FORWARD:
704                 if (!cur.selection()) {
705                         if (cur.pos() == cur.paragraph().size())
706                                 // Par boundary, force full-screen update
707                                 singleParUpdate = false;
708                         needsUpdate |= erase(cur);
709                         cur.resetAnchor();
710                         // It is possible to make it a lot faster still
711                         // just comment out the line below...
712                 } else {
713                         cutSelection(cur, true, false);
714                         singleParUpdate = false;
715                 }
716                 moveCursor(cur, false);
717                 break;
718
719         case LFUN_DELETE_FORWARD_SKIP:
720                 // Reverse the effect of LFUN_BREAK_PARAGRAPH_SKIP.
721                 if (!cur.selection()) {
722                         if (cur.pos() == cur.lastpos()) {
723                                 cursorForward(cur);
724                                 cursorBackward(cur);
725                         }
726                         erase(cur);
727                         cur.resetAnchor();
728                 } else {
729                         cutSelection(cur, true, false);
730                 }
731                 break;
732
733
734         case LFUN_CHAR_DELETE_BACKWARD:
735                 if (!cur.selection()) {
736                         if (bv->getIntl().getTransManager().backspace()) {
737                                 // Par boundary, full-screen update
738                                 if (cur.pos() == 0)
739                                         singleParUpdate = false;
740                                 needsUpdate |= backspace(cur);
741                                 cur.resetAnchor();
742                                 // It is possible to make it a lot faster still
743                                 // just comment out the line below...
744                         }
745                 } else {
746                         cutSelection(cur, true, false);
747                         singleParUpdate = false;
748                 }
749                 break;
750
751         case LFUN_DELETE_BACKWARD_SKIP:
752                 // Reverse the effect of LFUN_BREAK_PARAGRAPH_SKIP.
753                 if (!cur.selection()) {
754                         // FIXME: look here
755                         //CursorSlice cur = cursor();
756                         backspace(cur);
757                         //anchor() = cur;
758                 } else {
759                         cutSelection(cur, true, false);
760                 }
761                 break;
762
763         case LFUN_BREAK_PARAGRAPH:
764                 cap::replaceSelection(cur);
765                 breakParagraph(cur, cmd.argument() == "inverse");
766                 cur.resetAnchor();
767                 break;
768
769         case LFUN_BREAK_PARAGRAPH_SKIP: {
770                 // When at the beginning of a paragraph, remove
771                 // indentation.  Otherwise, do the same as LFUN_BREAK_PARAGRAPH.
772                 cap::replaceSelection(cur);
773                 if (cur.pos() == 0)
774                         cur.paragraph().params().labelWidthString(docstring());
775                 else
776                         breakParagraph(cur, false);
777                 cur.resetAnchor();
778                 break;
779         }
780
781         // TODO
782         // With the creation of LFUN_PARAGRAPH_PARAMS, this is now redundant,
783         // as its duties can be performed there. Should it be removed??
784         // FIXME For now, it can just dispatch LFUN_PARAGRAPH_PARAMS...
785         case LFUN_PARAGRAPH_SPACING: {
786                 Paragraph & par = cur.paragraph();
787                 Spacing::Space cur_spacing = par.params().spacing().getSpace();
788                 string cur_value = "1.0";
789                 if (cur_spacing == Spacing::Other)
790                         cur_value = par.params().spacing().getValueAsString();
791
792                 istringstream is(to_utf8(cmd.argument()));
793                 string tmp;
794                 is >> tmp;
795                 Spacing::Space new_spacing = cur_spacing;
796                 string new_value = cur_value;
797                 if (tmp.empty()) {
798                         lyxerr << "Missing argument to `paragraph-spacing'"
799                                << endl;
800                 } else if (tmp == "single") {
801                         new_spacing = Spacing::Single;
802                 } else if (tmp == "onehalf") {
803                         new_spacing = Spacing::Onehalf;
804                 } else if (tmp == "double") {
805                         new_spacing = Spacing::Double;
806                 } else if (tmp == "other") {
807                         new_spacing = Spacing::Other;
808                         string tmpval = "0.0";
809                         is >> tmpval;
810                         lyxerr << "new_value = " << tmpval << endl;
811                         if (tmpval != "0.0")
812                                 new_value = tmpval;
813                 } else if (tmp == "default") {
814                         new_spacing = Spacing::Default;
815                 } else {
816                         lyxerr << to_utf8(_("Unknown spacing argument: "))
817                                << to_utf8(cmd.argument()) << endl;
818                 }
819                 if (cur_spacing != new_spacing || cur_value != new_value)
820                         par.params().spacing(Spacing(new_spacing, new_value));
821                 break;
822         }
823
824         case LFUN_INSET_INSERT: {
825                 cur.recordUndo();
826                 Inset * inset = createInset(bv->buffer(), cmd);
827                 if (inset) {
828                         // FIXME (Abdel 01/02/2006):
829                         // What follows would be a partial fix for bug 2154:
830                         //   http://bugzilla.lyx.org/show_bug.cgi?id=2154
831                         // This automatically put the label inset _after_ a
832                         // numbered section. It should be possible to extend the mechanism
833                         // to any kind of LateX environement.
834                         // The correct way to fix that bug would be at LateX generation.
835                         // I'll let the code here for reference as it could be used for some
836                         // other feature like "automatic labelling".
837                         /*
838                         Paragraph & par = pars_[cur.pit()];
839                         if (inset->lyxCode() == LABEL_CODE
840                                 && par.layout()->labeltype == LABEL_COUNTER) {
841                                 // Go to the end of the paragraph
842                                 // Warning: Because of Change-Tracking, the last
843                                 // position is 'size()' and not 'size()-1':
844                                 cur.pos() = par.size();
845                                 // Insert a new paragraph
846                                 FuncRequest fr(LFUN_BREAK_PARAGRAPH);
847                                 dispatch(cur, fr);
848                         }
849                         */
850                         if (cur.selection())
851                                 cutSelection(cur, true, false);
852                         insertInset(cur, inset);
853                         cur.posForward();
854                 }
855                 break;
856         }
857
858         case LFUN_INSET_DISSOLVE:
859                 needsUpdate |= dissolveInset(cur);
860                 break;
861
862         case LFUN_INSET_SETTINGS:
863                 cur.inset().showInsetDialog(bv);
864                 break;
865
866         case LFUN_SPACE_INSERT:
867                 if (cur.paragraph().layout()->free_spacing)
868                         insertChar(cur, ' ');
869                 else {
870                         doInsertInset(cur, this, cmd, false, false);
871                         cur.posForward();
872                 }
873                 moveCursor(cur, false);
874                 break;
875
876         case LFUN_HYPHENATION_POINT_INSERT:
877                 specialChar(cur, InsetSpecialChar::HYPHENATION);
878                 break;
879
880         case LFUN_LIGATURE_BREAK_INSERT:
881                 specialChar(cur, InsetSpecialChar::LIGATURE_BREAK);
882                 break;
883
884         case LFUN_DOTS_INSERT:
885                 specialChar(cur, InsetSpecialChar::LDOTS);
886                 break;
887
888         case LFUN_END_OF_SENTENCE_PERIOD_INSERT:
889                 specialChar(cur, InsetSpecialChar::END_OF_SENTENCE);
890                 break;
891
892         case LFUN_MENU_SEPARATOR_INSERT:
893                 specialChar(cur, InsetSpecialChar::MENU_SEPARATOR);
894                 break;
895
896         case LFUN_WORD_UPCASE:
897                 changeCase(cur, text_uppercase);
898                 break;
899
900         case LFUN_WORD_LOWCASE:
901                 changeCase(cur, text_lowercase);
902                 break;
903
904         case LFUN_WORD_CAPITALIZE:
905                 changeCase(cur, text_capitalization);
906                 break;
907
908         case LFUN_CHARS_TRANSPOSE:
909                 charsTranspose(cur);
910                 break;
911
912         case LFUN_PASTE:
913                 cur.message(_("Paste"));
914                 cap::replaceSelection(cur);
915                 if (cmd.argument().empty() && !theClipboard().isInternal())
916                         pasteClipboard(cur, bv->buffer().errorList("Paste"));
917                 else {
918                         string const arg(to_utf8(cmd.argument()));
919                         pasteFromStack(cur, bv->buffer().errorList("Paste"),
920                                         isStrUnsignedInt(arg) ?
921                                                 convert<unsigned int>(arg) :
922                                                 0);
923                 }
924                 bv->buffer().errors("Paste");
925                 cur.clearSelection(); // bug 393
926                 cur.finishUndo();
927                 break;
928
929         case LFUN_CUT:
930                 cutSelection(cur, true, true);
931                 cur.message(_("Cut"));
932                 break;
933
934         case LFUN_COPY:
935                 copySelection(cur);
936                 cur.message(_("Copy"));
937                 break;
938
939         case LFUN_SERVER_GET_XY:
940                 cur.message(from_utf8(
941                         convert<string>(tm.cursorX(cur.top(), cur.boundary()))
942                         + ' ' + convert<string>(tm.cursorY(cur.top(), cur.boundary()))));
943                 break;
944
945         case LFUN_SERVER_SET_XY: {
946                 int x = 0;
947                 int y = 0;
948                 istringstream is(to_utf8(cmd.argument()));
949                 is >> x >> y;
950                 if (!is)
951                         lyxerr << "SETXY: Could not parse coordinates in '"
952                                << to_utf8(cmd.argument()) << std::endl;
953                 else
954                         tm.setCursorFromCoordinates(cur, x, y);
955                 break;
956         }
957
958         case LFUN_SERVER_GET_FONT:
959                 if (cur.current_font.fontInfo().shape() == ITALIC_SHAPE)
960                         cur.message(from_ascii("E"));
961                 else if (cur.current_font.fontInfo().shape() == SMALLCAPS_SHAPE)
962                         cur.message(from_ascii("N"));
963                 else
964                         cur.message(from_ascii("0"));
965                 break;
966
967         case LFUN_SERVER_GET_LAYOUT:
968                 cur.message(cur.paragraph().layout()->name());
969                 break;
970
971         case LFUN_LAYOUT: {
972                 docstring layout = cmd.argument();
973                 LYXERR(Debug::INFO, "LFUN_LAYOUT: (arg) " << to_utf8(layout));
974
975                 docstring const old_layout = cur.paragraph().layout()->name();
976
977                 // Derive layout number from given argument (string)
978                 // and current buffer's textclass (number)
979                 TextClass const & tclass = bv->buffer().params().getTextClass();
980                 if (layout.empty())
981                         layout = tclass.defaultLayoutName();
982                 bool hasLayout = tclass.hasLayout(layout);
983
984                 // If the entry is obsolete, use the new one instead.
985                 if (hasLayout) {
986                         docstring const & obs = tclass[layout]->obsoleted_by();
987                         if (!obs.empty())
988                                 layout = obs;
989                 }
990
991                 if (!hasLayout) {
992                         cur.errorMessage(from_utf8(N_("Layout ")) + cmd.argument() +
993                                 from_utf8(N_(" not known")));
994                         break;
995                 }
996
997                 bool change_layout = (old_layout != layout);
998
999                 if (!change_layout && cur.selection() &&
1000                         cur.selBegin().pit() != cur.selEnd().pit())
1001                 {
1002                         pit_type spit = cur.selBegin().pit();
1003                         pit_type epit = cur.selEnd().pit() + 1;
1004                         while (spit != epit) {
1005                                 if (pars_[spit].layout()->name() != old_layout) {
1006                                         change_layout = true;
1007                                         break;
1008                                 }
1009                                 ++spit;
1010                         }
1011                 }
1012
1013                 if (change_layout)
1014                         setLayout(cur, layout);
1015
1016                 break;
1017         }
1018
1019         case LFUN_CLIPBOARD_PASTE:
1020                 cur.clearSelection();
1021                 pasteClipboard(cur, bv->buffer().errorList("Paste"),
1022                                cmd.argument() == "paragraph");
1023                 bv->buffer().errors("Paste");
1024                 break;
1025
1026         case LFUN_PRIMARY_SELECTION_PASTE:
1027                 pasteString(cur, theSelection().get(),
1028                             cmd.argument() == "paragraph");
1029                 break;
1030
1031         case LFUN_UNICODE_INSERT: {
1032                 if (cmd.argument().empty())
1033                         break;
1034                 docstring hexstring = cmd.argument();
1035                 if (lyx::support::isHex(hexstring)) {
1036                         char_type c = lyx::support::hexToInt(hexstring);
1037                         if (c >= 32 && c < 0x10ffff) {
1038                                 lyxerr << "Inserting c: " << c << endl;
1039                                 docstring s = docstring(1, c);
1040                                 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, s));
1041                         }
1042                 }
1043                 break;
1044         }
1045
1046         case LFUN_QUOTE_INSERT: {
1047                 Paragraph & par = cur.paragraph();
1048                 pos_type pos = cur.pos();
1049                 BufferParams const & bufparams = bv->buffer().params();
1050                 LayoutPtr const & style = par.layout();
1051                 if (!style->pass_thru
1052                     && par.getFontSettings(bufparams, pos).language()->lang() != "hebrew") {
1053                         // this avoids a double undo
1054                         // FIXME: should not be needed, ideally
1055                         if (!cur.selection())
1056                                 cur.recordUndo();
1057                         cap::replaceSelection(cur);
1058                         pos = cur.pos();
1059                         char_type c;
1060                         if (pos == 0)
1061                                 c = ' ';
1062                         else if (cur.prevInset() && cur.prevInset()->isSpace())
1063                                 c = ' ';
1064                         else
1065                                 c = par.getChar(pos - 1);
1066                         string arg = to_utf8(cmd.argument());
1067                         if (arg == "single")
1068                                 cur.insert(new InsetQuotes(c,
1069                                     bufparams.quotes_language,
1070                                     InsetQuotes::SingleQ));
1071                         else
1072                                 cur.insert(new InsetQuotes(c,
1073                                     bufparams.quotes_language,
1074                                     InsetQuotes::DoubleQ));
1075                         cur.posForward();
1076                 }
1077                 else
1078                         lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, "\""));
1079                 break;
1080         }
1081
1082         case LFUN_DATE_INSERT: {
1083                 string const format = cmd.argument().empty()
1084                         ? lyxrc.date_insert_format : to_utf8(cmd.argument());
1085                 string const time = formatted_time(current_time(), format);
1086                 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, time));
1087                 break;
1088         }
1089
1090         case LFUN_MOUSE_TRIPLE:
1091                 if (cmd.button() == mouse_button::button1) {
1092                         tm.cursorHome(cur);
1093                         cur.resetAnchor();
1094                         tm.cursorEnd(cur);
1095                         cur.setSelection();
1096                         bv->cursor() = cur;
1097                 }
1098                 break;
1099
1100         case LFUN_MOUSE_DOUBLE:
1101                 if (cmd.button() == mouse_button::button1) {
1102                         selectWord(cur, WHOLE_WORD_STRICT);
1103                         bv->cursor() = cur;
1104                 }
1105                 break;
1106
1107         // Single-click on work area
1108         case LFUN_MOUSE_PRESS: {
1109                 // Right click on a footnote flag opens float menu
1110                 // FIXME: Why should we clear the selection in this case?
1111                 if (cmd.button() == mouse_button::button3)
1112                         cur.clearSelection();
1113
1114                 bool do_selection = cmd.button() == mouse_button::button1
1115                         && cmd.argument() == "region-select";
1116                 // Set the cursor
1117                 bool update = bv->mouseSetCursor(cur, do_selection);
1118
1119                 // Insert primary selection with middle mouse
1120                 // if there is a local selection in the current buffer,
1121                 // insert this
1122                 if (cmd.button() == mouse_button::button2) {
1123                         if (cap::selection()) {
1124                                 // Copy the selection buffer to the clipboard
1125                                 // stack, because we want it to appear in the
1126                                 // "Edit->Paste recent" menu.
1127                                 cap::copySelectionToStack();
1128
1129                                 cap::pasteSelection(bv->cursor(), 
1130                                                     bv->buffer().errorList("Paste"));
1131                                 bv->buffer().errors("Paste");
1132                                 bv->buffer().markDirty();
1133                                 bv->cursor().finishUndo();
1134                         } else {
1135                                 lyx::dispatch(FuncRequest(LFUN_PRIMARY_SELECTION_PASTE, "paragraph"));
1136                         }
1137                 }
1138
1139                 // we have to update after dEPM triggered
1140                 if (!update && cmd.button() == mouse_button::button1) {
1141                         needsUpdate = false;
1142                         cur.noUpdate();
1143                 }
1144
1145                 break;
1146         }
1147
1148         case LFUN_MOUSE_MOTION: {
1149                 // Only use motion with button 1
1150                 //if (cmd.button() != mouse_button::button1)
1151                 //      return false;
1152
1153                 // ignore motions deeper nested than the real anchor
1154                 Cursor & bvcur = cur.bv().cursor();
1155                 if (!bvcur.anchor_.hasPart(cur)) {
1156                         cur.undispatched();
1157                         break;
1158                 }
1159                 CursorSlice old = bvcur.top();
1160
1161                 int const wh = bv->workHeight();
1162                 int const y = std::max(0, std::min(wh - 1, cmd.y));
1163
1164                 tm.setCursorFromCoordinates(cur, cmd.x, y);
1165                 cur.setTargetX(cmd.x);
1166                 if (cmd.y >= wh)
1167                         lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1168                 else if (cmd.y < 0)
1169                         lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1170                 // This is to allow jumping over large insets
1171                 if (cur.top() == old) {
1172                         if (cmd.y >= wh)
1173                                 lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1174                         else if (cmd.y < 0)
1175                                 lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1176                 }
1177
1178                 if (cur.top() == old)
1179                         cur.noUpdate();
1180                 else {
1181                         // FIXME: This is brute force! But without it the selected
1182                         // area is not corrected updated while moving the mouse.
1183                         cur.updateFlags(Update::Force | Update::FitCursor);
1184                         // don't set anchor_
1185                         bvcur.setCursor(cur);
1186                         bvcur.selection() = true;
1187                         //lyxerr << "MOTION: " << bv->cursor() << endl;
1188                 }
1189                 break;
1190         }
1191
1192         case LFUN_MOUSE_RELEASE: {
1193                 if (cmd.button() == mouse_button::button2)
1194                         break;
1195
1196                 if (cmd.button() == mouse_button::button1) {
1197                         // if there is new selection, update persistent
1198                         // selection, otherwise, single click does not
1199                         // clear persistent selection buffer
1200                         if (cur.selection()) {
1201                                 // finish selection
1202                                 // if double click, cur is moved to the end of word by selectWord
1203                                 // but bvcur is current mouse position
1204                                 Cursor & bvcur = cur.bv().cursor();
1205                                 bvcur.selection() = true;
1206                         }
1207                         needsUpdate = false;
1208                         cur.noUpdate();
1209                 }
1210
1211                 break;
1212         }
1213
1214         case LFUN_SELF_INSERT: {
1215                 if (cmd.argument().empty())
1216                         break;
1217
1218                 // Automatically delete the currently selected
1219                 // text and replace it with what is being
1220                 // typed in now. Depends on lyxrc settings
1221                 // "auto_region_delete", which defaults to
1222                 // true (on).
1223
1224                 if (lyxrc.auto_region_delete && cur.selection())
1225                         cutSelection(cur, false, false);
1226
1227                 cur.clearSelection();
1228                 Font const old_font = cur.real_current_font;
1229
1230                 docstring::const_iterator cit = cmd.argument().begin();
1231                 docstring::const_iterator end = cmd.argument().end();
1232                 for (; cit != end; ++cit)
1233                         bv->translateAndInsert(*cit, this, cur);
1234
1235                 cur.resetAnchor();
1236                 moveCursor(cur, false);
1237                 break;
1238         }
1239
1240         case LFUN_HYPERLINK_INSERT: {
1241                 InsetCommandParams p(HYPERLINK_CODE);
1242                 docstring content;
1243                 if (cur.selection()) {
1244                         content = cur.selectionAsString(false);
1245                         cutSelection(cur, true, false);
1246                 }
1247                 p["target"] = (cmd.argument().empty()) ?
1248                         content : cmd.argument();
1249                 string const data = InsetCommandMailer::params2string("href", p);
1250                 if (p["target"].empty()) {
1251                         bv->showDialog("href", data);
1252                 } else {
1253                         FuncRequest fr(LFUN_INSET_INSERT, data);
1254                         dispatch(cur, fr);
1255                 }
1256                 break;
1257         }
1258
1259         case LFUN_LABEL_INSERT: {
1260                 InsetCommandParams p(LABEL_CODE);
1261                 // Try to generate a valid label
1262                 p["name"] = (cmd.argument().empty()) ?
1263                         cur.getPossibleLabel() :
1264                         cmd.argument();
1265                 string const data = InsetCommandMailer::params2string("label", p);
1266
1267                 if (cmd.argument().empty()) {
1268                         bv->showDialog("label", data);
1269                 } else {
1270                         FuncRequest fr(LFUN_INSET_INSERT, data);
1271                         dispatch(cur, fr);
1272                 }
1273                 break;
1274         }
1275
1276         case LFUN_INFO_INSERT: {
1277                 Inset * inset = createInset(cur.bv().buffer(), cmd);
1278                 if (!inset)
1279                         break;
1280                 // if an empty inset is created (cmd.argument() is empty)
1281                 // use current selection as parameter.
1282                 if (cmd.argument().empty() && cur.selection()) {
1283                         // use selected text as info to avoid a separate UI
1284                         docstring ds = cur.selectionAsString(false);
1285                         cutSelection(cur, true, false);
1286                         static_cast<InsetInfo *>(inset)->setInfo(to_utf8(ds));
1287                 }
1288                 insertInset(cur, inset);
1289                 cur.posForward();
1290                 break;
1291         }
1292 #if 0
1293         case LFUN_LIST_INSERT:
1294         case LFUN_THEOREM_INSERT:
1295 #endif
1296         case LFUN_CAPTION_INSERT:
1297         case LFUN_FOOTNOTE_INSERT:
1298                 // Open the inset, and move the current selection
1299                 // inside it.
1300                 doInsertInset(cur, this, cmd, true, true);
1301                 cur.posForward();
1302                 // These insets are numbered.
1303                 updateLabels(bv->buffer());
1304                 break;
1305         case LFUN_NOTE_INSERT:
1306         case LFUN_FLEX_INSERT:
1307         case LFUN_BOX_INSERT:
1308         case LFUN_BRANCH_INSERT:
1309         case LFUN_BIBITEM_INSERT:
1310         case LFUN_ERT_INSERT:
1311         case LFUN_LISTING_INSERT:
1312         case LFUN_MARGINALNOTE_INSERT:
1313         case LFUN_OPTIONAL_INSERT:
1314         case LFUN_ENVIRONMENT_INSERT:
1315                 // Open the inset, and move the current selection
1316                 // inside it.
1317                 doInsertInset(cur, this, cmd, true, true);
1318                 cur.posForward();
1319                 break;
1320
1321         case LFUN_TABULAR_INSERT:
1322                 // if there were no arguments, just open the dialog
1323                 if (doInsertInset(cur, this, cmd, false, true))
1324                         cur.posForward();
1325                 else
1326                         bv->showDialog("tabularcreate");
1327
1328                 break;
1329
1330         case LFUN_FLOAT_INSERT:
1331         case LFUN_FLOAT_WIDE_INSERT:
1332         case LFUN_WRAP_INSERT: {
1333                 bool content = cur.selection();  // will some text be moved into the inset?
1334
1335                 doInsertInset(cur, this, cmd, true, true);
1336                 cur.posForward();
1337                 ParagraphList & pars = cur.text()->paragraphs();
1338
1339                 TextClass const & tclass = bv->buffer().params().getTextClass();
1340
1341                 // add a separate paragraph for the caption inset
1342                 pars.push_back(Paragraph());
1343                 pars.back().setInsetOwner(pars[0].inInset());
1344                 pars.back().layout(tclass.defaultLayout());
1345
1346                 int cap_pit = pars.size() - 1;
1347
1348                 // if an empty inset was created, we create an additional empty
1349                 // paragraph at the bottom so that the user can choose where to put
1350                 // the graphics (or table).
1351                 if (!content) {
1352                         pars.push_back(Paragraph());
1353                         pars.back().setInsetOwner(pars[0].inInset());
1354                         pars.back().layout(tclass.defaultLayout());
1355
1356                 }
1357
1358                 // reposition the cursor to the caption
1359                 cur.pit() = cap_pit;
1360                 cur.pos() = 0;
1361                 // FIXME: This Text/Cursor dispatch handling is a mess!
1362                 // We cannot use Cursor::dispatch here it needs access to up to
1363                 // date metrics.
1364                 FuncRequest cmd_caption(LFUN_CAPTION_INSERT);
1365                 cur.text()->dispatch(cur, cmd_caption);
1366                 cur.updateFlags(Update::Force);
1367                 // FIXME: When leaving the Float (or Wrap) inset we should
1368                 // delete any empty paragraph left above or below the
1369                 // caption.
1370                 break;
1371         }
1372
1373         case LFUN_INDEX_INSERT:
1374                 doInsertInset(cur, this, cmd, true, true);
1375                 cur.posForward();
1376                 break;
1377
1378         case LFUN_NOMENCL_INSERT: {
1379                 FuncRequest cmd1 = cmd;
1380                 if (cmd.argument().empty())
1381                         cmd1 = FuncRequest(cmd,
1382                                 bv->cursor().innerText()->getStringToIndex(bv->cursor()));
1383                 Inset * inset = createInset(cur.bv().buffer(), cmd1);
1384                 if (!inset)
1385                         break;
1386                 cur.recordUndo();
1387                 cur.clearSelection();
1388                 insertInset(cur, inset);
1389                 // Show the dialog for the nomenclature entry, since the
1390                 // description entry still needs to be filled in.
1391                 if (cmd.action == LFUN_NOMENCL_INSERT)
1392                         inset->edit(cur, true);
1393                 cur.posForward();
1394                 break;
1395         }
1396
1397         case LFUN_INDEX_PRINT:
1398         case LFUN_NOMENCL_PRINT:
1399         case LFUN_TOC_INSERT:
1400         case LFUN_HFILL_INSERT:
1401         case LFUN_LINE_INSERT:
1402         case LFUN_NEWPAGE_INSERT:
1403         case LFUN_PAGEBREAK_INSERT:
1404         case LFUN_CLEARPAGE_INSERT:
1405         case LFUN_CLEARDOUBLEPAGE_INSERT:
1406                 // do nothing fancy
1407                 doInsertInset(cur, this, cmd, false, false);
1408                 cur.posForward();
1409                 break;
1410
1411         case LFUN_DEPTH_DECREMENT:
1412                 changeDepth(cur, DEC_DEPTH);
1413                 break;
1414
1415         case LFUN_DEPTH_INCREMENT:
1416                 changeDepth(cur, INC_DEPTH);
1417                 break;
1418
1419         case LFUN_MATH_DISPLAY:
1420                 mathDispatch(cur, cmd, true);
1421                 break;
1422
1423         case LFUN_MATH_IMPORT_SELECTION:
1424         case LFUN_MATH_MODE:
1425                 if (cmd.argument() == "on")
1426                         // don't pass "on" as argument
1427                         mathDispatch(cur, FuncRequest(LFUN_MATH_MODE), false);
1428                 else
1429                         mathDispatch(cur, cmd, false);
1430                 break;
1431
1432         case LFUN_MATH_MACRO:
1433                 if (cmd.argument().empty())
1434                         cur.errorMessage(from_utf8(N_("Missing argument")));
1435                 else {
1436                         string s = to_utf8(cmd.argument());
1437                         string const s1 = token(s, ' ', 1);
1438                         int const nargs = s1.empty() ? 0 : convert<int>(s1);
1439                         string const s2 = token(s, ' ', 2);
1440                         string const type = s2.empty() ? "newcommand" : s2;
1441                         cur.insert(new MathMacroTemplate(from_utf8(token(s, ' ', 0)), nargs, false, from_utf8(type)));
1442                         //cur.nextInset()->edit(cur, true);
1443                 }
1444                 break;
1445
1446         // passthrough hat and underscore outside mathed:
1447         case LFUN_MATH_SUBSCRIPT:
1448                 mathDispatch(cur, FuncRequest(LFUN_SELF_INSERT, "_"), false);
1449                 break;
1450         case LFUN_MATH_SUPERSCRIPT:
1451                 mathDispatch(cur, FuncRequest(LFUN_SELF_INSERT, "^"), false);
1452                 break;
1453
1454         case LFUN_MATH_INSERT:
1455         case LFUN_MATH_MATRIX:
1456         case LFUN_MATH_DELIM:
1457         case LFUN_MATH_BIGDELIM: {
1458                 if (cur.selection())
1459                         cur.clearSelection();
1460                 // FIXME: instead of the above, this one
1461                 // should be used (but it asserts with Bidi enabled)
1462                 // cf. http://bugzilla.lyx.org/show_bug.cgi?id=4055
1463                 // cap::replaceSelection(cur);
1464                 cur.insert(new InsetMathHull(hullSimple));
1465                 checkAndActivateInset(cur, true);
1466                 BOOST_ASSERT(cur.inMathed());
1467                 cur.dispatch(cmd);
1468                 break;
1469         }
1470
1471         case LFUN_FONT_EMPH: {
1472                 Font font(ignore_font, ignore_language);
1473                 font.fontInfo().setEmph(FONT_TOGGLE);
1474                 toggleAndShow(cur, this, font);
1475                 break;
1476         }
1477
1478         case LFUN_FONT_BOLD: {
1479                 Font font(ignore_font, ignore_language);
1480                 font.fontInfo().setSeries(BOLD_SERIES);
1481                 toggleAndShow(cur, this, font);
1482                 break;
1483         }
1484
1485         case LFUN_FONT_NOUN: {
1486                 Font font(ignore_font, ignore_language);
1487                 font.fontInfo().setNoun(FONT_TOGGLE);
1488                 toggleAndShow(cur, this, font);
1489                 break;
1490         }
1491
1492         case LFUN_FONT_TYPEWRITER: {
1493                 Font font(ignore_font, ignore_language);
1494                 font.fontInfo().setFamily(TYPEWRITER_FAMILY); // no good
1495                 toggleAndShow(cur, this, font);
1496                 break;
1497         }
1498
1499         case LFUN_FONT_SANS: {
1500                 Font font(ignore_font, ignore_language);
1501                 font.fontInfo().setFamily(SANS_FAMILY);
1502                 toggleAndShow(cur, this, font);
1503                 break;
1504         }
1505
1506         case LFUN_FONT_ROMAN: {
1507                 Font font(ignore_font, ignore_language);
1508                 font.fontInfo().setFamily(ROMAN_FAMILY);
1509                 toggleAndShow(cur, this, font);
1510                 break;
1511         }
1512
1513         case LFUN_FONT_DEFAULT: {
1514                 Font font(inherit_font, ignore_language);
1515                 toggleAndShow(cur, this, font);
1516                 break;
1517         }
1518
1519         case LFUN_FONT_UNDERLINE: {
1520                 Font font(ignore_font, ignore_language);
1521                 font.fontInfo().setUnderbar(FONT_TOGGLE);
1522                 toggleAndShow(cur, this, font);
1523                 break;
1524         }
1525
1526         case LFUN_FONT_SIZE: {
1527                 Font font(ignore_font, ignore_language);
1528                 setLyXSize(to_utf8(cmd.argument()), font.fontInfo());
1529                 toggleAndShow(cur, this, font);
1530                 break;
1531         }
1532
1533         case LFUN_LANGUAGE: {
1534                 Language const * lang = languages.getLanguage(to_utf8(cmd.argument()));
1535                 if (!lang)
1536                         break;
1537                 Font font(ignore_font, lang);
1538                 toggleAndShow(cur, this, font);
1539                 break;
1540         }
1541
1542         case LFUN_FONT_FREE_APPLY:
1543                 toggleAndShow(cur, this, freefont, toggleall);
1544                 cur.message(_("Character set"));
1545                 break;
1546
1547         // Set the freefont using the contents of \param data dispatched from
1548         // the frontends and apply it at the current cursor location.
1549         case LFUN_FONT_FREE_UPDATE: {
1550                 Font font;
1551                 bool toggle;
1552                 if (font.fromString(to_utf8(cmd.argument()), toggle)) {
1553                         freefont = font;
1554                         toggleall = toggle;
1555                         toggleAndShow(cur, this, freefont, toggleall);
1556                         cur.message(_("Character set"));
1557                 } else {
1558                         lyxerr << "Argument not ok";
1559                 }
1560                 break;
1561         }
1562
1563         case LFUN_FINISHED_LEFT:
1564                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_LEFT:\n" << cur);
1565                 if (reverseDirectionNeeded(cur)) {
1566                         ++cur.pos();
1567                         cur.setCurrentFont();
1568                 }
1569                 break;
1570
1571         case LFUN_FINISHED_RIGHT:
1572                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_RIGHT:\n" << cur);
1573                 if (!reverseDirectionNeeded(cur)) {
1574                         ++cur.pos();
1575                         cur.setCurrentFont();
1576                 }
1577                 break;
1578
1579         case LFUN_FINISHED_BACKWARD:
1580                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_BACKWARD:\n" << cur);
1581                 break;
1582
1583         case LFUN_FINISHED_FORWARD:
1584                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_FORWARD:\n" << cur);
1585                 ++cur.pos();
1586                 cur.setCurrentFont();
1587                 break;
1588
1589         case LFUN_LAYOUT_PARAGRAPH: {
1590                 string data;
1591                 params2string(cur.paragraph(), data);
1592                 data = "show\n" + data;
1593                 bv->showDialog("paragraph", data);
1594                 break;
1595         }
1596
1597         case LFUN_PARAGRAPH_UPDATE: {
1598                 string data;
1599                 params2string(cur.paragraph(), data);
1600
1601                 // Will the paragraph accept changes from the dialog?
1602                 bool const accept = !cur.inset().forceDefaultParagraphs(cur.idx());
1603
1604                 data = "update " + convert<string>(accept) + '\n' + data;
1605                 bv->updateDialog("paragraph", data);
1606                 break;
1607         }
1608
1609         case LFUN_ACCENT_UMLAUT:
1610         case LFUN_ACCENT_CIRCUMFLEX:
1611         case LFUN_ACCENT_GRAVE:
1612         case LFUN_ACCENT_ACUTE:
1613         case LFUN_ACCENT_TILDE:
1614         case LFUN_ACCENT_CEDILLA:
1615         case LFUN_ACCENT_MACRON:
1616         case LFUN_ACCENT_DOT:
1617         case LFUN_ACCENT_UNDERDOT:
1618         case LFUN_ACCENT_UNDERBAR:
1619         case LFUN_ACCENT_CARON:
1620         case LFUN_ACCENT_SPECIAL_CARON:
1621         case LFUN_ACCENT_BREVE:
1622         case LFUN_ACCENT_TIE:
1623         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
1624         case LFUN_ACCENT_CIRCLE:
1625         case LFUN_ACCENT_OGONEK:
1626                 theLyXFunc().handleKeyFunc(cmd.action);
1627                 if (!cmd.argument().empty())
1628                         // FIXME: Are all these characters encoded in one byte in utf8?
1629                         bv->translateAndInsert(cmd.argument()[0], this, cur);
1630                 break;
1631
1632         case LFUN_FLOAT_LIST: {
1633                 TextClass const & tclass = bv->buffer().params().getTextClass();
1634                 if (tclass.floats().typeExist(to_utf8(cmd.argument()))) {
1635                         cur.recordUndo();
1636                         if (cur.selection())
1637                                 cutSelection(cur, true, false);
1638                         breakParagraph(cur);
1639
1640                         if (cur.lastpos() != 0) {
1641                                 cursorBackward(cur);
1642                                 breakParagraph(cur);
1643                         }
1644
1645                         setLayout(cur, tclass.defaultLayoutName());
1646                         ParagraphParameters p;
1647                         setParagraphs(cur, p);
1648                         insertInset(cur, new InsetFloatList(to_utf8(cmd.argument())));
1649                         cur.posForward();
1650                 } else {
1651                         lyxerr << "Non-existent float type: "
1652                                << to_utf8(cmd.argument()) << endl;
1653                 }
1654                 break;
1655         }
1656
1657         case LFUN_CHANGE_ACCEPT: {
1658                 acceptOrRejectChanges(cur, ACCEPT);
1659                 break;
1660         }
1661
1662         case LFUN_CHANGE_REJECT: {
1663                 acceptOrRejectChanges(cur, REJECT);
1664                 break;
1665         }
1666
1667         case LFUN_THESAURUS_ENTRY: {
1668                 docstring arg = cmd.argument();
1669                 if (arg.empty()) {
1670                         arg = cur.selectionAsString(false);
1671                         // FIXME
1672                         if (arg.size() > 100 || arg.empty()) {
1673                                 // Get word or selection
1674                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
1675                                 arg = cur.selectionAsString(false);
1676                         }
1677                 }
1678                 bv->showDialog("thesaurus", to_utf8(arg));
1679                 break;
1680         }
1681
1682         case LFUN_PARAGRAPH_PARAMS_APPLY: {
1683                 // Given data, an encoding of the ParagraphParameters
1684                 // generated in the Paragraph dialog, this function sets
1685                 // the current paragraph, or currently selected paragraphs,
1686                 // appropriately. 
1687                 // NOTE: This function overrides all existing settings.
1688                 setParagraphs(cur, cmd.argument());
1689                 cur.message(_("Paragraph layout set"));
1690                 break;
1691         }
1692         
1693         case LFUN_PARAGRAPH_PARAMS: {
1694                 // Given data, an encoding of the ParagraphParameters as we'd
1695                 // find them in a LyX file, this function modifies the current paragraph, 
1696                 // or currently selected paragraphs. 
1697                 // NOTE: This function only modifies, and does not override, existing
1698                 // settings.
1699                 setParagraphs(cur, cmd.argument(), true);
1700                 cur.message(_("Paragraph layout set"));
1701                 break;
1702         }
1703
1704         case LFUN_ESCAPE:
1705                 if (cur.selection()) {
1706                         cur.selection() = false;
1707                 } else {
1708                         cur.undispatched();
1709                         // This used to be LFUN_FINISHED_RIGHT, I think FORWARD is more
1710                         // correct, but I'm not 100% sure -- dov, 071019
1711                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
1712                 }
1713                 break;
1714
1715         case LFUN_OUTLINE_UP:
1716                 outline(OutlineUp, cur);
1717                 setCursor(cur, cur.pit(), 0);
1718                 updateLabels(cur.buffer());
1719                 needsUpdate = true;
1720                 break;
1721
1722         case LFUN_OUTLINE_DOWN:
1723                 outline(OutlineDown, cur);
1724                 setCursor(cur, cur.pit(), 0);
1725                 updateLabels(cur.buffer());
1726                 needsUpdate = true;
1727                 break;
1728
1729         case LFUN_OUTLINE_IN:
1730                 outline(OutlineIn, cur);
1731                 updateLabels(cur.buffer());
1732                 needsUpdate = true;
1733                 break;
1734
1735         case LFUN_OUTLINE_OUT:
1736                 outline(OutlineOut, cur);
1737                 updateLabels(cur.buffer());
1738                 needsUpdate = true;
1739                 break;
1740
1741         default:
1742                 LYXERR(Debug::ACTION, BOOST_CURRENT_FUNCTION
1743                         << ": Command " << cmd << " not DISPATCHED by Text");
1744                 cur.undispatched();
1745                 break;
1746         }
1747
1748         needsUpdate |= (cur.pos() != cur.lastpos()) && cur.selection();
1749
1750         // FIXME: The cursor flag is reset two lines below
1751         // so we need to check here if some of the LFUN did touch that.
1752         // for now only Text::erase() and Text::backspace() do that.
1753         // The plan is to verify all the LFUNs and then to remove this
1754         // singleParUpdate boolean altogether.
1755         if (cur.result().update() & Update::Force) {
1756                 singleParUpdate = false;
1757                 needsUpdate = true;
1758         }
1759
1760         // FIXME: the following code should go in favor of fine grained
1761         // update flag treatment.
1762         if (singleParUpdate) {
1763                 // Inserting characters does not change par height
1764                 ParagraphMetrics const & pms
1765                         = cur.bv().parMetrics(cur.bottom().text(), cur.bottom().pit());
1766                 if (pms.dim().height() == olddim.height()) {
1767                         // if so, update _only_ this paragraph
1768                         cur.updateFlags(Update::SinglePar |
1769                                 Update::FitCursor);
1770                         return;
1771                 }
1772                 needsUpdate = true;
1773         }
1774
1775         if (!needsUpdate
1776             && &oldTopSlice.inset() == &cur.inset()
1777             && oldTopSlice.idx() == cur.idx()
1778             && !sel // sel is a backup of cur.selection() at the biginning of the function.
1779             && !cur.selection())
1780                 // FIXME: it would be better if we could just do this
1781                 //
1782                 //if (cur.result().update() != Update::FitCursor)
1783                 //      cur.noUpdate();
1784                 //
1785                 // But some LFUNs do not set Update::FitCursor when needed, so we
1786                 // do it for all. This is not very harmfull as FitCursor will provoke
1787                 // a full redraw only if needed but still, a proper review of all LFUN
1788                 // should be done and this needsUpdate boolean can then be removed.
1789                 cur.updateFlags(Update::FitCursor);
1790         else
1791                 cur.updateFlags(Update::Force | Update::FitCursor);
1792 }
1793
1794
1795 bool Text::getStatus(Cursor & cur, FuncRequest const & cmd,
1796                         FuncStatus & flag) const
1797 {
1798         BOOST_ASSERT(cur.text() == this);
1799
1800         Font const & font = cur.real_current_font;
1801         FontInfo const & fontinfo = font.fontInfo();
1802         bool enable = true;
1803         InsetCode code = NO_CODE;
1804
1805         switch (cmd.action) {
1806
1807         case LFUN_DEPTH_DECREMENT:
1808                 enable = changeDepthAllowed(cur, DEC_DEPTH);
1809                 break;
1810
1811         case LFUN_DEPTH_INCREMENT:
1812                 enable = changeDepthAllowed(cur, INC_DEPTH);
1813                 break;
1814
1815         case LFUN_APPENDIX:
1816                 flag.setOnOff(cur.paragraph().params().startOfAppendix());
1817                 return true;
1818
1819         case LFUN_BIBITEM_INSERT:
1820                 enable = (cur.paragraph().layout()->labeltype == LABEL_BIBLIO
1821                           && cur.pos() == 0);
1822                 break;
1823
1824         case LFUN_DIALOG_SHOW_NEW_INSET:
1825                 if (cmd.argument() == "bibitem")
1826                         code = BIBITEM_CODE;
1827                 else if (cmd.argument() == "bibtex")
1828                         code = BIBTEX_CODE;
1829                 else if (cmd.argument() == "box")
1830                         code = BOX_CODE;
1831                 else if (cmd.argument() == "branch")
1832                         code = BRANCH_CODE;
1833                 else if (cmd.argument() == "citation")
1834                         code = CITE_CODE;
1835                 else if (cmd.argument() == "ert")
1836                         code = ERT_CODE;
1837                 else if (cmd.argument() == "external")
1838                         code = EXTERNAL_CODE;
1839                 else if (cmd.argument() == "float")
1840                         code = FLOAT_CODE;
1841                 else if (cmd.argument() == "graphics")
1842                         code = GRAPHICS_CODE;
1843                 else if (cmd.argument() == "href")
1844                         code = HYPERLINK_CODE;
1845                 else if (cmd.argument() == "include")
1846                         code = INCLUDE_CODE;
1847                 else if (cmd.argument() == "index")
1848                         code = INDEX_CODE;
1849                 else if (cmd.argument() == "nomenclature")
1850                         code = NOMENCL_CODE;
1851                 else if (cmd.argument() == "label")
1852                         code = LABEL_CODE;
1853                 else if (cmd.argument() == "note")
1854                         code = NOTE_CODE;
1855                 else if (cmd.argument() == "ref")
1856                         code = REF_CODE;
1857                 else if (cmd.argument() == "toc")
1858                         code = TOC_CODE;
1859                 else if (cmd.argument() == "vspace")
1860                         code = VSPACE_CODE;
1861                 else if (cmd.argument() == "wrap")
1862                         code = WRAP_CODE;
1863                 else if (cmd.argument() == "listings")
1864                         code = LISTINGS_CODE;
1865                 break;
1866
1867         case LFUN_ERT_INSERT:
1868                 code = ERT_CODE;
1869                 break;
1870         case LFUN_LISTING_INSERT:
1871             code = LISTINGS_CODE;
1872                 break;
1873         case LFUN_FOOTNOTE_INSERT:
1874                 code = FOOT_CODE;
1875                 break;
1876         case LFUN_TABULAR_INSERT:
1877                 code = TABULAR_CODE;
1878                 break;
1879         case LFUN_MARGINALNOTE_INSERT:
1880                 code = MARGIN_CODE;
1881                 break;
1882         case LFUN_FLOAT_INSERT:
1883         case LFUN_FLOAT_WIDE_INSERT:
1884                 code = FLOAT_CODE;
1885                 break;
1886         case LFUN_WRAP_INSERT:
1887                 code = WRAP_CODE;
1888                 break;
1889         case LFUN_FLOAT_LIST:
1890                 code = FLOAT_LIST_CODE;
1891                 break;
1892 #if 0
1893         case LFUN_LIST_INSERT:
1894                 code = LIST_CODE;
1895                 break;
1896         case LFUN_THEOREM_INSERT:
1897                 code = THEOREM_CODE;
1898                 break;
1899 #endif
1900         case LFUN_CAPTION_INSERT:
1901                 code = CAPTION_CODE;
1902                 break;
1903         case LFUN_NOTE_INSERT:
1904                 code = NOTE_CODE;
1905                 break;
1906         case LFUN_FLEX_INSERT: {
1907                 code = FLEX_CODE;
1908                 string s = cmd.getArg(0);
1909                 InsetLayout il =  cur.buffer().params().getTextClass().insetlayout(from_utf8(s));
1910                 if (il.lyxtype != "charstyle" &&
1911                     il.lyxtype != "custom" &&
1912                     il.lyxtype != "element" &&
1913                     il.lyxtype != "standard")
1914                         enable = false;
1915                 break;
1916                 }
1917         case LFUN_BOX_INSERT:
1918                 code = BOX_CODE;
1919                 break;
1920         case LFUN_BRANCH_INSERT:
1921                 code = BRANCH_CODE;
1922                 if (cur.buffer().masterBuffer()->params().branchlist().empty())
1923                         enable = false;
1924                 break;
1925         case LFUN_LABEL_INSERT:
1926                 code = LABEL_CODE;
1927                 break;
1928         case LFUN_INFO_INSERT:
1929                 code = INFO_CODE;
1930                 break;
1931         case LFUN_OPTIONAL_INSERT:
1932                 code = OPTARG_CODE;
1933                 enable = cur.paragraph().insetList().count(OPTARG_CODE)
1934                         < cur.paragraph().layout()->optionalargs;
1935                 break;
1936         case LFUN_ENVIRONMENT_INSERT:
1937                 code = BOX_CODE;
1938                 break;
1939         case LFUN_INDEX_INSERT:
1940                 code = INDEX_CODE;
1941                 break;
1942         case LFUN_INDEX_PRINT:
1943                 code = INDEX_PRINT_CODE;
1944                 break;
1945         case LFUN_NOMENCL_INSERT:
1946                 code = NOMENCL_CODE;
1947                 break;
1948         case LFUN_NOMENCL_PRINT:
1949                 code = NOMENCL_PRINT_CODE;
1950                 break;
1951         case LFUN_TOC_INSERT:
1952                 code = TOC_CODE;
1953                 break;
1954         case LFUN_HYPERLINK_INSERT:
1955                 code = HYPERLINK_CODE;
1956                 break;
1957         case LFUN_QUOTE_INSERT:
1958                 // always allow this, since we will inset a raw quote
1959                 // if an inset is not allowed.
1960                 break;
1961         case LFUN_HYPHENATION_POINT_INSERT:
1962         case LFUN_LIGATURE_BREAK_INSERT:
1963         case LFUN_HFILL_INSERT:
1964         case LFUN_MENU_SEPARATOR_INSERT:
1965         case LFUN_DOTS_INSERT:
1966         case LFUN_END_OF_SENTENCE_PERIOD_INSERT:
1967                 code = SPECIALCHAR_CODE;
1968                 break;
1969         case LFUN_SPACE_INSERT:
1970                 // slight hack: we know this is allowed in math mode
1971                 if (cur.inTexted())
1972                         code = SPACE_CODE;
1973                 break;
1974
1975         case LFUN_INSET_MODIFY:
1976                 // We need to disable this, because we may get called for a
1977                 // tabular cell via
1978                 // InsetTabular::getStatus() -> InsetText::getStatus()
1979                 // and we don't handle LFUN_INSET_MODIFY.
1980                 enable = false;
1981                 break;
1982
1983         case LFUN_FONT_EMPH:
1984                 flag.setOnOff(fontinfo.emph() == FONT_ON);
1985                 return true;
1986
1987         case LFUN_FONT_NOUN:
1988                 flag.setOnOff(fontinfo.noun() == FONT_ON);
1989                 return true;
1990
1991         case LFUN_FONT_BOLD:
1992                 flag.setOnOff(fontinfo.series() == BOLD_SERIES);
1993                 return true;
1994
1995         case LFUN_FONT_SANS:
1996                 flag.setOnOff(fontinfo.family() == SANS_FAMILY);
1997                 return true;
1998
1999         case LFUN_FONT_ROMAN:
2000                 flag.setOnOff(fontinfo.family() == ROMAN_FAMILY);
2001                 return true;
2002
2003         case LFUN_FONT_TYPEWRITER:
2004                 flag.setOnOff(fontinfo.family() == TYPEWRITER_FAMILY);
2005                 return true;
2006
2007         case LFUN_CUT:
2008         case LFUN_COPY:
2009                 enable = cur.selection();
2010                 break;
2011
2012         case LFUN_PASTE:
2013                 if (cmd.argument().empty()) {
2014                         if (theClipboard().isInternal())
2015                                 enable = cap::numberOfSelections() > 0;
2016                         else
2017                                 enable = !theClipboard().empty();
2018                 } else {
2019                         string const arg = to_utf8(cmd.argument());
2020                         if (isStrUnsignedInt(arg)) {
2021                                 unsigned int n = convert<unsigned int>(arg);
2022                                 enable = cap::numberOfSelections() > n;
2023                         } else
2024                                 // unknown argument
2025                                 enable = false;
2026                 }
2027                 break;
2028
2029         case LFUN_CLIPBOARD_PASTE:
2030                 enable = !theClipboard().empty();
2031                 break;
2032
2033         case LFUN_PRIMARY_SELECTION_PASTE:
2034                 enable = cur.selection() || !theSelection().empty();
2035                 break;
2036
2037         case LFUN_PARAGRAPH_MOVE_UP:
2038                 enable = cur.pit() > 0 && !cur.selection();
2039                 break;
2040
2041         case LFUN_PARAGRAPH_MOVE_DOWN:
2042                 enable = cur.pit() < cur.lastpit() && !cur.selection();
2043                 break;
2044
2045         case LFUN_INSET_DISSOLVE:
2046                 if (!cmd.argument().empty()) {
2047                         InsetLayout il = cur.inset().getLayout(cur.buffer().params());
2048                         enable = cur.inset().lyxCode() == FLEX_CODE
2049                                  && il.lyxtype == to_utf8(cmd.argument());
2050                 } else {
2051                         enable = !isMainText(cur.bv().buffer()) 
2052                                  && cur.inset().nargs() == 1;
2053                 }
2054                 break;
2055
2056         case LFUN_CHANGE_ACCEPT:
2057         case LFUN_CHANGE_REJECT:
2058                 // TODO: context-sensitive enabling of LFUN_CHANGE_ACCEPT/REJECT
2059                 // In principle, these LFUNs should only be enabled if there
2060                 // is a change at the current position/in the current selection.
2061                 // However, without proper optimizations, this will inevitably
2062                 // result in unacceptable performance - just imagine a user who
2063                 // wants to select the complete content of a long document.
2064                 enable = true;
2065                 break;
2066
2067         case LFUN_OUTLINE_UP:
2068         case LFUN_OUTLINE_DOWN:
2069         case LFUN_OUTLINE_IN:
2070         case LFUN_OUTLINE_OUT:
2071                 enable = (cur.paragraph().layout()->toclevel != Layout::NOT_IN_TOC);
2072                 break;
2073
2074         case LFUN_WORD_DELETE_FORWARD:
2075         case LFUN_WORD_DELETE_BACKWARD:
2076         case LFUN_LINE_DELETE:
2077         case LFUN_WORD_FORWARD:
2078         case LFUN_WORD_BACKWARD:
2079         case LFUN_WORD_RIGHT:
2080         case LFUN_WORD_LEFT:
2081         case LFUN_CHAR_FORWARD:
2082         case LFUN_CHAR_FORWARD_SELECT:
2083         case LFUN_CHAR_BACKWARD:
2084         case LFUN_CHAR_BACKWARD_SELECT:
2085         case LFUN_CHAR_LEFT:
2086         case LFUN_CHAR_LEFT_SELECT:
2087         case LFUN_CHAR_RIGHT:
2088         case LFUN_CHAR_RIGHT_SELECT:
2089         case LFUN_UP:
2090         case LFUN_UP_SELECT:
2091         case LFUN_DOWN:
2092         case LFUN_DOWN_SELECT:
2093         case LFUN_PARAGRAPH_UP_SELECT:
2094         case LFUN_PARAGRAPH_DOWN_SELECT:
2095         case LFUN_SCREEN_UP_SELECT:
2096         case LFUN_SCREEN_DOWN_SELECT:
2097         case LFUN_LINE_BEGIN_SELECT:
2098         case LFUN_LINE_END_SELECT:
2099         case LFUN_WORD_FORWARD_SELECT:
2100         case LFUN_WORD_BACKWARD_SELECT:
2101         case LFUN_WORD_RIGHT_SELECT:
2102         case LFUN_WORD_LEFT_SELECT:
2103         case LFUN_WORD_SELECT:
2104         case LFUN_PARAGRAPH_UP:
2105         case LFUN_PARAGRAPH_DOWN:
2106         case LFUN_LINE_BEGIN:
2107         case LFUN_LINE_BREAK:
2108         case LFUN_LINE_END:
2109         case LFUN_NEW_LINE:
2110         case LFUN_CHAR_DELETE_FORWARD:
2111         case LFUN_DELETE_FORWARD_SKIP:
2112         case LFUN_CHAR_DELETE_BACKWARD:
2113         case LFUN_DELETE_BACKWARD_SKIP:
2114         case LFUN_BREAK_PARAGRAPH:
2115         case LFUN_BREAK_PARAGRAPH_SKIP:
2116         case LFUN_PARAGRAPH_SPACING:
2117         case LFUN_INSET_INSERT:
2118         case LFUN_WORD_UPCASE:
2119         case LFUN_WORD_LOWCASE:
2120         case LFUN_WORD_CAPITALIZE:
2121         case LFUN_CHARS_TRANSPOSE:
2122         case LFUN_SERVER_GET_XY:
2123         case LFUN_SERVER_SET_XY:
2124         case LFUN_SERVER_GET_FONT:
2125         case LFUN_SERVER_GET_LAYOUT:
2126         case LFUN_LAYOUT:
2127         case LFUN_DATE_INSERT:
2128         case LFUN_SELF_INSERT:
2129         case LFUN_LINE_INSERT:
2130         case LFUN_NEWPAGE_INSERT:
2131         case LFUN_PAGEBREAK_INSERT:
2132         case LFUN_CLEARPAGE_INSERT:
2133         case LFUN_CLEARDOUBLEPAGE_INSERT:
2134         case LFUN_MATH_DISPLAY:
2135         case LFUN_MATH_IMPORT_SELECTION:
2136         case LFUN_MATH_MODE:
2137         case LFUN_MATH_MACRO:
2138         case LFUN_MATH_MATRIX:
2139         case LFUN_MATH_DELIM:
2140         case LFUN_MATH_BIGDELIM:
2141         case LFUN_MATH_INSERT:
2142         case LFUN_MATH_SUBSCRIPT:
2143         case LFUN_MATH_SUPERSCRIPT:
2144         case LFUN_FONT_DEFAULT:
2145         case LFUN_FONT_UNDERLINE:
2146         case LFUN_FONT_SIZE:
2147         case LFUN_LANGUAGE:
2148         case LFUN_FONT_FREE_APPLY:
2149         case LFUN_FONT_FREE_UPDATE:
2150         case LFUN_LAYOUT_PARAGRAPH:
2151         case LFUN_PARAGRAPH_UPDATE:
2152         case LFUN_ACCENT_UMLAUT:
2153         case LFUN_ACCENT_CIRCUMFLEX:
2154         case LFUN_ACCENT_GRAVE:
2155         case LFUN_ACCENT_ACUTE:
2156         case LFUN_ACCENT_TILDE:
2157         case LFUN_ACCENT_CEDILLA:
2158         case LFUN_ACCENT_MACRON:
2159         case LFUN_ACCENT_DOT:
2160         case LFUN_ACCENT_UNDERDOT:
2161         case LFUN_ACCENT_UNDERBAR:
2162         case LFUN_ACCENT_CARON:
2163         case LFUN_ACCENT_SPECIAL_CARON:
2164         case LFUN_ACCENT_BREVE:
2165         case LFUN_ACCENT_TIE:
2166         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
2167         case LFUN_ACCENT_CIRCLE:
2168         case LFUN_ACCENT_OGONEK:
2169         case LFUN_THESAURUS_ENTRY:
2170         case LFUN_PARAGRAPH_PARAMS_APPLY:
2171         case LFUN_PARAGRAPH_PARAMS:
2172         case LFUN_ESCAPE:
2173         case LFUN_BUFFER_END:
2174         case LFUN_BUFFER_BEGIN:
2175         case LFUN_BUFFER_BEGIN_SELECT:
2176         case LFUN_BUFFER_END_SELECT:
2177         case LFUN_UNICODE_INSERT:
2178                 // these are handled in our dispatch()
2179                 enable = true;
2180                 break;
2181
2182         default:
2183                 return false;
2184         }
2185
2186         if (code != NO_CODE
2187             && (cur.empty() || !cur.inset().insetAllowed(code)))
2188                 enable = false;
2189
2190         flag.enabled(enable);
2191         return true;
2192 }
2193
2194
2195 void Text::pasteString(Cursor & cur, docstring const & clip,
2196                 bool asParagraphs)
2197 {
2198         cur.clearSelection();
2199         if (!clip.empty()) {
2200                 cur.recordUndo();
2201                 if (asParagraphs)
2202                         insertStringAsParagraphs(cur, clip);
2203                 else
2204                         insertStringAsLines(cur, clip);
2205         }
2206 }
2207
2208 } // namespace lyx