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