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