]> git.lyx.org Git - lyx.git/blob - src/BufferView_pimpl.C
f5f1be2b2dadde664b78e2cc4fe440d6d73f6fd8
[lyx.git] / src / BufferView_pimpl.C
1 #include <config.h>
2
3 #ifdef __GNUG__
4 #pragma implementation
5 #endif
6
7 #include "BufferView_pimpl.h"
8 #include "WorkArea.h"
9 #include "lyxscreen.h"
10 #include "lyxtext.h"
11 #include "lyxrow.h"
12 #include "paragraph.h"
13 #include "LyXView.h"
14 #include "commandtags.h"
15 #include "lyxfunc.h"
16 #include "debug.h"
17 #include "font.h"
18 #include "bufferview_funcs.h"
19 #include "TextCache.h"
20 #include "bufferlist.h"
21 #include "lyx_gui_misc.h"
22 #include "lyxrc.h"
23 #include "intl.h"
24 // added for Dispatch functions
25 #include "lyx_cb.h"
26 #include "lyx_main.h"
27 #include "FloatList.h"
28 #include "gettext.h"
29 #include "ParagraphParameters.h"
30 #include "undo_funcs.h"
31 #include "lyxtextclasslist.h"
32
33 #include "frontends/Dialogs.h"
34 #include "frontends/Alert.h"
35 #include "frontends/FileDialog.h"
36
37 #include "insets/insetbib.h"
38 #include "insets/insettext.h"
39 #include "insets/inseturl.h"
40 #include "insets/insetlatexaccent.h"
41 #include "insets/insettoc.h"
42 #include "insets/insetref.h"
43 #include "insets/insetparent.h"
44 #include "insets/insetindex.h"
45 #include "insets/insetnote.h"
46 #include "insets/insetinclude.h"
47 #include "insets/insetcite.h"
48 #include "insets/insetert.h"
49 #include "insets/insetexternal.h"
50 #include "insets/insetgraphics.h"
51 #include "insets/insetfoot.h"
52 #include "insets/insetmarginal.h"
53 #include "insets/insetminipage.h"
54 #include "insets/insetfloat.h"
55 #include "insets/insettabular.h"
56 #if 0
57 #include "insets/insettheorem.h"
58 #include "insets/insetlist.h"
59 #endif
60 #include "insets/insetcaption.h"
61 #include "insets/insetfloatlist.h"
62 #include "insets/insetspecialchar.h"
63
64 #include "mathed/formulabase.h"
65
66 #include "support/LAssert.h"
67 #include "support/lstrings.h"
68 #include "support/filetools.h"
69 #include "support/lyxfunctional.h"
70
71 #include <ctime>
72 #include <unistd.h>
73 #include <sys/wait.h>
74 #include <clocale>
75
76
77 extern lyx::layout_type current_layout;
78
79 using std::vector;
80 using std::find_if;
81 using std::find;
82 using std::pair;
83 using std::endl;
84 using std::make_pair;
85 using std::min;
86 using SigC::slot;
87
88 using lyx::pos_type;
89 using lyx::layout_type;
90 using lyx::textclass_type;
91
92 /* the selection possible is needed, that only motion events are 
93  * used, where the bottom press event was on the drawing area too */
94 bool selection_possible = false;
95
96 extern BufferList bufferlist;
97 extern char ascii_type;
98
99 extern void sigchldchecker(pid_t pid, int * status);
100 extern int bibitemMaxWidth(BufferView *, LyXFont const &);
101
102
103 namespace {
104
105 const unsigned int saved_positions_num = 20;
106
107 inline
108 void waitForX()
109 {
110         XSync(fl_get_display(), 0);
111 }
112
113
114 void SetXtermCursor(Window win)
115 {
116         static Cursor cursor;
117         static bool cursor_undefined = true;
118         if (cursor_undefined) {
119                 cursor = XCreateFontCursor(fl_get_display(), XC_xterm);
120                 XFlush(fl_get_display());
121                 cursor_undefined = false;
122         }
123         XDefineCursor(fl_get_display(), win, cursor);
124         XFlush(fl_get_display());
125 }
126
127 } // anon namespace
128
129
130 BufferView::Pimpl::Pimpl(BufferView * b, LyXView * o,
131              int xpos, int ypos, int width, int height)
132         : bv_(b), owner_(o), buffer_(0),
133           current_scrollbar_value(0), cursor_timeout(400),
134           workarea_(xpos, ypos, width, height), using_xterm_cursor(false),
135           inset_slept(false)
136 {
137         // Setup the signals
138         workarea_.scrollCB.connect(slot(this, &BufferView::Pimpl::scrollCB));
139         workarea_.workAreaExpose
140                 .connect(slot(this, &BufferView::Pimpl::workAreaExpose));
141         workarea_.workAreaEnter
142                 .connect(slot(this, &BufferView::Pimpl::enterView));
143         workarea_.workAreaLeave
144                 .connect(slot(this, &BufferView::Pimpl::leaveView));
145         workarea_.workAreaButtonPress
146                 .connect(slot(this, &BufferView::Pimpl::workAreaButtonPress));
147         workarea_.workAreaButtonRelease
148                 .connect(slot(this,
149                               &BufferView::Pimpl::workAreaButtonRelease));
150         workarea_.workAreaMotionNotify
151                 .connect(slot(this, &BufferView::Pimpl::workAreaMotionNotify));
152         workarea_.workAreaDoubleClick
153                 .connect(slot(this, &BufferView::Pimpl::doubleClick));
154         workarea_.workAreaTripleClick
155                 .connect(slot(this, &BufferView::Pimpl::tripleClick));
156         workarea_.workAreaKeyPress
157                 .connect(slot(this, &BufferView::Pimpl::workAreaKeyPress));
158         workarea_.selectionRequested
159                 .connect(slot(this, &BufferView::Pimpl::selectionRequested)); 
160         workarea_.selectionLost
161                 .connect(slot(this, &BufferView::Pimpl::selectionLost));
162         
163         cursor_timeout.timeout.connect(slot(this,
164                                             &BufferView::Pimpl::cursorToggle));
165         cursor_timeout.start();
166         workarea_.setFocus();
167         saved_positions.resize(saved_positions_num);
168 }
169
170
171 Painter & BufferView::Pimpl::painter() 
172 {
173         return workarea_.getPainter();
174 }
175
176
177 void BufferView::Pimpl::buffer(Buffer * b)
178 {
179         lyxerr[Debug::INFO] << "Setting buffer in BufferView ("
180                             << b << ")" << endl;
181         if (buffer_) {
182                 insetSleep();
183                 buffer_->delUser(bv_);
184
185                 // Put the old text into the TextCache, but
186                 // only if the buffer is still loaded.
187                 // Also set the owner of the test to 0
188                 //              bv_->text->owner(0);
189                 textcache.add(buffer_, workarea_.workWidth(), bv_->text);
190                 if (lyxerr.debugging())
191                         textcache.show(lyxerr, "BufferView::buffer");
192                 
193                 bv_->text = 0;
194         }
195
196         // Set current buffer
197         buffer_ = b;
198
199         if (bufferlist.getState() == BufferList::CLOSING) return;
200         
201         // Nuke old image
202         // screen is always deleted when the buffer is changed.
203         screen_.reset(0);
204
205         // If we are closing the buffer, use the first buffer as current
206         if (!buffer_) {
207                 buffer_ = bufferlist.first();
208         }
209
210         if (buffer_) {
211                 lyxerr[Debug::INFO] << "Buffer addr: " << buffer_ << endl;
212                 buffer_->addUser(bv_);
213                 // If we don't have a text object for this, we make one
214                 if (bv_->text == 0) {
215                         resizeCurrentBuffer();
216                 } else {
217                         updateScreen();
218                         updateScrollbar();
219                 }
220                 bv_->text->first = screen_->topCursorVisible(bv_->text);
221                 owner_->updateMenubar();
222                 owner_->updateToolbar();
223                 // Similarly, buffer-dependent dialogs should be updated or
224                 // hidden. This should go here because some dialogs (eg ToC)
225                 // require bv_->text.
226                 owner_->getDialogs()->updateBufferDependent(true);
227                 redraw();
228                 insetWakeup();
229         } else {
230                 lyxerr[Debug::INFO] << "  No Buffer!" << endl;
231                 owner_->updateMenubar();
232                 owner_->updateToolbar();
233                 owner_->getDialogs()->hideBufferDependent();
234                 updateScrollbar();
235                 workarea_.redraw();
236
237                 // Also remove all remaining text's from the testcache.
238                 // (there should not be any!) (if there is any it is a
239                 // bug!)
240                 if (lyxerr.debugging())
241                         textcache.show(lyxerr, "buffer delete all");
242                 textcache.clear();
243         }
244         // should update layoutchoice even if we don't have a buffer.
245         owner_->updateLayoutChoice();
246
247         owner_->updateWindowTitle();
248 }
249
250
251 void BufferView::Pimpl::resize(int xpos, int ypos, int width, int height)
252 {
253         workarea_.resize(xpos, ypos, width, height);
254         update(bv_->text, SELECT);
255         redraw();
256 }
257
258
259 void BufferView::Pimpl::resize()
260 {
261         if (buffer_)
262                 resizeCurrentBuffer();
263 }
264
265
266 void BufferView::Pimpl::redraw()
267 {
268         lyxerr[Debug::INFO] << "BufferView::redraw()" << endl;
269         workarea_.redraw();
270 }
271
272
273 bool BufferView::Pimpl::fitCursor()
274 {
275         lyx::Assert(screen_.get());
276
277         bool ret;
278
279         if (bv_->theLockingInset()) {
280                 bv_->theLockingInset()->fitInsetCursor(bv_);
281                 ret = true;
282         } else {
283                 ret = screen_->fitCursor(bv_->text, bv_);
284         }
285
286         bv_->owner()->getDialogs()->updateParagraph();
287         if (ret)
288             updateScrollbar();
289         return ret;
290 }
291
292
293 void BufferView::Pimpl::redoCurrentBuffer()
294 {
295         lyxerr[Debug::INFO] << "BufferView::redoCurrentBuffer" << endl;
296         if (buffer_ && bv_->text) {
297                 resize();
298                 owner_->updateLayoutChoice();
299         }
300 }
301
302
303 int BufferView::Pimpl::resizeCurrentBuffer()
304 {
305         lyxerr[Debug::INFO] << "resizeCurrentBuffer" << endl;
306         
307         Paragraph * par = 0;
308         Paragraph * selstartpar = 0;
309         Paragraph * selendpar = 0;
310         UpdatableInset * the_locking_inset = 0;
311         
312         pos_type pos = 0;
313         pos_type selstartpos = 0;
314         pos_type selendpos = 0;
315         bool selection = false;
316         bool mark_set  = false;
317
318         owner_->prohibitInput();
319
320         owner_->message(_("Formatting document..."));
321
322         if (bv_->text) {
323                 par = bv_->text->cursor.par();
324                 pos = bv_->text->cursor.pos();
325                 selstartpar = bv_->text->selection.start.par();
326                 selstartpos = bv_->text->selection.start.pos();
327                 selendpar = bv_->text->selection.end.par();
328                 selendpos = bv_->text->selection.end.pos();
329                 selection = bv_->text->selection.set();
330                 mark_set = bv_->text->selection.mark();
331                 the_locking_inset = bv_->theLockingInset();
332                 delete bv_->text;
333                 bv_->text = new LyXText(bv_);
334                 bv_->text->init(bv_);
335         } else {
336                 // See if we have a text in TextCache that fits
337                 // the new buffer_ with the correct width.
338                 bv_->text = textcache.findFit(buffer_, workarea_.workWidth());
339                 if (bv_->text) {
340                         if (lyxerr.debugging()) {
341                                 lyxerr << "Found a LyXText that fits:\n";
342                                 textcache.show(lyxerr, make_pair(buffer_, make_pair(workarea_.workWidth(), bv_->text)));
343                         }
344                         // Set the owner of the newly found text
345                         //      bv_->text->owner(bv_);
346                         if (lyxerr.debugging())
347                                 textcache.show(lyxerr, "resizeCurrentBuffer");
348                 } else {
349                         bv_->text = new LyXText(bv_);
350                         bv_->text->init(bv_);
351                 }
352         }
353         updateScreen();
354
355         if (par) {
356                 bv_->text->selection.set(true);
357                 /* at this point just to avoid the Delete-Empty-Paragraph
358                  * Mechanism when setting the cursor */
359                 bv_->text->selection.mark(mark_set);
360                 if (selection) {
361                         bv_->text->setCursor(bv_, selstartpar, selstartpos);
362                         bv_->text->selection.cursor = bv_->text->cursor;
363                         bv_->text->setCursor(bv_, selendpar, selendpos);
364                         bv_->text->setSelection(bv_);
365                         bv_->text->setCursor(bv_, par, pos);
366                 } else {
367                         bv_->text->setCursor(bv_, par, pos);
368                         bv_->text->selection.cursor = bv_->text->cursor;
369                         bv_->text->selection.set(false);
370                 }
371                 // remake the inset locking
372                 bv_->theLockingInset(the_locking_inset);
373         }
374         bv_->text->first = screen_->topCursorVisible(bv_->text);
375 #if 0
376         buffer_->resizeInsets(bv_);
377 #endif
378         // this will scroll the screen such that the cursor becomes visible
379         updateScrollbar();
380         redraw();
381
382         setState();
383         owner_->allowInput();
384
385         /// clear the "Formatting Document" message 
386         owner_->message("");
387
388         return 0;
389 }
390
391
392 void BufferView::Pimpl::updateScreen()
393 {
394         // Regenerate the screen.
395         screen_.reset(new LyXScreen(workarea_));
396 }
397
398
399 void BufferView::Pimpl::updateScrollbar()
400 {
401         /* If the text is smaller than the working area, the scrollbar
402          * maximum must be the working area height. No scrolling will 
403          * be possible */
404         if (!bv_->text) {
405                 workarea_.setScrollbar(0, 1.0);
406                 return;
407         }
408
409         long const text_height = bv_->text->height;
410         long const work_height = workarea_.height();
411
412         if (text_height <= work_height) {
413                 workarea_.setScrollbarBounds(0.0, 0.0);
414                 current_scrollbar_value = bv_->text->first;
415                 workarea_.setScrollbar(current_scrollbar_value, 1.0);
416                 return;
417         }
418         
419         double const lineh = bv_->text->defaultHeight();
420         double const slider_size =
421                 (text_height == 0) ? 1.0 : 1.0 / double(text_height);
422         
423         static long old_text_height;
424         static double old_lineh;
425         static double old_slider_size;
426
427         if (text_height != old_text_height) {
428                 workarea_.setScrollbarBounds(0.0,
429                                              text_height - work_height);
430                 old_text_height = text_height;
431         }
432         if (lineh != old_lineh) {
433                 workarea_.setScrollbarIncrements(lineh);
434                 old_lineh = lineh;
435         }
436         if (current_scrollbar_value != bv_->text->first
437             || slider_size != old_slider_size) {
438                 current_scrollbar_value = bv_->text->first;
439                 workarea_.setScrollbar(current_scrollbar_value, slider_size);
440                 old_slider_size = slider_size;
441         }
442 }
443
444
445 // Callback for scrollbar slider
446 void BufferView::Pimpl::scrollCB(double value)
447 {
448         if (!buffer_) return;
449
450         current_scrollbar_value = long(value);
451
452         if (current_scrollbar_value < 0)
453                 current_scrollbar_value = 0;
454    
455         if (!screen_.get())
456                 return;
457
458         screen_->draw(bv_->text, bv_, current_scrollbar_value);
459
460         if (!lyxrc.cursor_follows_scrollbar) {
461                 waitForX();
462                 return;
463         }
464  
465         LyXText * vbt = bv_->text;
466  
467         int const height = vbt->defaultHeight();
468         int const first = static_cast<int>((bv_->text->first + height));
469         int const last = static_cast<int>((bv_->text->first + workarea_.height() - height));
470
471         if (vbt->cursor.y() < first)
472                 vbt->setCursorFromCoordinates(bv_, 0, first);
473         else if (vbt->cursor.y() > last)
474                 vbt->setCursorFromCoordinates(bv_, 0, last);
475
476         waitForX();
477 }
478
479
480 int BufferView::Pimpl::scrollUp(long time)
481 {
482         if (!buffer_) return 0;
483         if (!screen_.get()) return 0;
484    
485         double value = workarea_.getScrollbarValue();
486    
487         if (value == 0) return 0;
488
489         float add_value =  (bv_->text->defaultHeight()
490                             + float(time) * float(time) * 0.125);
491    
492         if (add_value > workarea_.height())
493                 add_value = float(workarea_.height() -
494                                   bv_->text->defaultHeight());
495    
496         value -= add_value;
497
498         if (value < 0)
499                 value = 0;
500    
501         workarea_.setScrollbarValue(value);
502    
503         scrollCB(value); 
504         return 0;
505 }
506
507
508 int BufferView::Pimpl::scrollDown(long time)
509 {
510         if (!buffer_) return 0;
511         if (!screen_.get()) return 0;
512    
513         double value = workarea_.getScrollbarValue();
514         pair<float, float> p = workarea_.getScrollbarBounds();
515         double const max = p.second;
516         
517         if (value == max) return 0;
518
519         float add_value =  (bv_->text->defaultHeight()
520                             + float(time) * float(time) * 0.125);
521    
522         if (add_value > workarea_.height())
523                 add_value = float(workarea_.height() -
524                                   bv_->text->defaultHeight());
525    
526         value += add_value;
527    
528         if (value > max)
529                 value = max;
530
531         workarea_.setScrollbarValue(value);
532         
533         scrollCB(value); 
534         return 0;
535 }
536
537
538 void BufferView::Pimpl::workAreaKeyPress(KeySym keysym, unsigned int state)
539 {
540         bv_->owner()->getLyXFunc()->processKeySym(keysym, state);
541 }
542
543
544 void BufferView::Pimpl::workAreaMotionNotify(int x, int y, unsigned int state)
545 {
546         // Only use motion with button 1
547         if (!(state & Button1MotionMask))
548                 return;
549
550         if (!buffer_ || !screen_.get()) return;
551
552         // Check for inset locking
553         if (bv_->theLockingInset()) {
554                 LyXCursor cursor = bv_->text->cursor;
555                 LyXFont font = bv_->text->getFont(buffer_,
556                                                   cursor.par(), cursor.pos());
557                 int width = bv_->theLockingInset()->width(bv_, font);
558                 int inset_x = font.isVisibleRightToLeft()
559                         ? cursor.x() - width : cursor.x();
560                 int start_x = inset_x + bv_->theLockingInset()->scroll();
561                 bv_->theLockingInset()->
562                         insetMotionNotify(bv_,
563                                           x - start_x,
564                                           y - cursor.y() + bv_->text->first,
565                                           state);
566                 return;
567         }
568    
569         /* The test for not selection possible is needed, that only motion
570            events are used, where the bottom press event was on
571            the drawing area too */
572         if (!selection_possible)
573                 return;
574  
575         screen_->hideCursor();
576
577         bv_->text->setCursorFromCoordinates(bv_, x, y + bv_->text->first);
578       
579         if (!bv_->text->selection.set())
580                 update(bv_->text, BufferView::UPDATE); // Maybe an empty line was deleted
581       
582         bv_->text->setSelection(bv_);
583         screen_->toggleToggle(bv_->text, bv_);
584         fitCursor();
585         showCursor();
586 }
587
588
589 // Single-click on work area
590 void BufferView::Pimpl::workAreaButtonPress(int xpos, int ypos,
591                                             unsigned int button)
592 {
593         if (!buffer_ || !screen_.get()) return;
594
595         Inset * inset_hit = checkInsetHit(bv_->text, xpos, ypos);
596
597         // ok ok, this is a hack.
598         if (button == 4 || button == 5) {
599                 switch (button) {
600                 case 4:
601                         scrollUp(lyxrc.wheel_jump); // default 100, set in lyxrc
602                         break;
603                 case 5:
604                         scrollDown(lyxrc.wheel_jump);
605                         break;
606                 }
607         }
608         
609         if (bv_->theLockingInset()) {
610                 // We are in inset locking mode
611                 
612                 /* Check whether the inset was hit. If not reset mode,
613                    otherwise give the event to the inset */
614                 if (inset_hit == bv_->theLockingInset()) {
615                         bv_->theLockingInset()->
616                                 insetButtonPress(bv_,xpos, ypos,button);
617                         return;
618                 } else {
619                         bv_->unlockInset(bv_->theLockingInset());
620                 }
621         }
622         
623         if (!inset_hit)
624                 selection_possible = true;
625         screen_->hideCursor();
626
627         int const screen_first = bv_->text->first;
628         
629         // Middle button press pastes if we have a selection
630         bool paste_internally = false;
631         if (button == 2
632             && bv_->text->selection.set()) {
633                 owner_->getLyXFunc()->dispatch(LFUN_COPY);
634                 paste_internally = true;
635         }
636         
637         // Clear the selection
638         screen_->toggleSelection(bv_->text, bv_);
639         bv_->text->clearSelection();
640         bv_->text->fullRebreak(bv_);
641         update();
642         updateScrollbar();
643         
644         // Single left click in math inset?
645         if (isHighlyEditableInset(inset_hit)) {
646                 // Highly editable inset, like math
647                 UpdatableInset * inset = static_cast<UpdatableInset *>(inset_hit);
648                 selection_possible = false;
649                 owner_->updateLayoutChoice();
650                 owner_->message(inset->editMessage());
651                 // IMO the inset has to be first in edit-mode and then we send the
652                 // button press. (Jug 20020222)
653                 inset->edit(bv_); //, xpos, ypos, button);
654                 inset->insetButtonPress(bv_, xpos, ypos, button);
655                 return;
656         } 
657         
658         // Right click on a footnote flag opens float menu
659         if (button == 3) { 
660                 selection_possible = false;
661                 return;
662         }
663         
664         if (!inset_hit) // otherwise it was already set in checkInsetHit(...)
665                 bv_->text->setCursorFromCoordinates(bv_, xpos, ypos + screen_first);
666         finishUndo();
667         bv_->text->selection.cursor = bv_->text->cursor;
668         bv_->text->cursor.x_fix(bv_->text->cursor.x());
669         
670         owner_->updateLayoutChoice();
671         if (fitCursor()) {
672                 selection_possible = false;
673         }
674         
675         // Insert primary selection with middle mouse
676         // if there is a local selection in the current buffer,
677         // insert this
678         if (button == 2) {
679                 if (paste_internally)
680                         owner_->getLyXFunc()->dispatch(LFUN_PASTE);
681                 else
682                         owner_->getLyXFunc()->dispatch(LFUN_PASTESELECTION,
683                                                        "paragraph");
684                 selection_possible = false;
685                 return;
686         }
687 }
688
689
690 void BufferView::Pimpl::doubleClick(int /*x*/, int /*y*/, unsigned int button) 
691 {
692         // select a word
693         if (!buffer_)
694                 return;
695
696         LyXText * text = bv_->getLyXText();
697
698         if (text->bv_owner && bv_->theLockingInset())
699                 return;
700
701         if (screen_.get() && button == 1) {
702                 if (text->bv_owner) {
703                         screen_->hideCursor();
704                         screen_->toggleSelection(text, bv_);
705                         text->selectWord(bv_, LyXText::WHOLE_WORD_STRICT);
706                         screen_->toggleSelection(text, bv_, false);
707                 } else {
708                         text->selectWord(bv_, LyXText::WHOLE_WORD_STRICT);
709                 }
710                 /* This will fit the cursor on the screen
711                  * if necessary */
712                 update(text, BufferView::SELECT|BufferView::FITCUR);
713         }
714 }
715
716
717 void BufferView::Pimpl::tripleClick(int /*x*/, int /*y*/, unsigned int button)
718 {
719         // select a line
720         if (!buffer_)
721                 return;
722
723         LyXText * text = bv_->getLyXText();
724
725         if (text->bv_owner && bv_->theLockingInset())
726             return;
727
728         if (screen_.get() && (button == 1)) {
729                 if (text->bv_owner) {
730                         screen_->hideCursor();
731                         screen_->toggleSelection(text, bv_);
732                 }
733                 text->cursorHome(bv_);
734                 text->selection.cursor = text->cursor;
735                 text->cursorEnd(bv_);
736                 text->setSelection(bv_);
737                 if (text->bv_owner) {
738                         screen_->toggleSelection(text, bv_, false);
739                 }
740                 /* This will fit the cursor on the screen
741                  * if necessary */
742                 update(text, BufferView::SELECT|BufferView::FITCUR);
743         }
744 }
745
746
747 void BufferView::Pimpl::selectionRequested()
748 {
749         if (!available())
750                 return;
751  
752         string const sel(bv_->getLyXText()->selectionAsString(bv_->buffer(),
753                                                               false)); 
754         if (!sel.empty()) {
755                 workarea_.putClipboard(sel);
756         }
757 }
758
759  
760 void BufferView::Pimpl::selectionLost()
761 {
762         hideCursor();
763         toggleSelection();
764         bv_->getLyXText()->clearSelection();
765         showCursor(); 
766 }
767
768  
769 void BufferView::Pimpl::enterView()
770 {
771         if (active() && available()) {
772                 SetXtermCursor(workarea_.getWin());
773                 using_xterm_cursor = true;
774         }
775 }
776
777
778 void BufferView::Pimpl::leaveView()
779 {
780         if (using_xterm_cursor) {
781                 XUndefineCursor(fl_get_display(), workarea_.getWin());
782                 using_xterm_cursor = false;
783         }
784 }
785
786
787 void BufferView::Pimpl::workAreaButtonRelease(int x, int y,
788                                               unsigned int button)
789 {
790         if (!buffer_ || !screen_.get()) return;
791
792         // If we hit an inset, we have the inset coordinates in these
793         // and inset_hit points to the inset.  If we do not hit an
794         // inset, inset_hit is 0, and inset_x == x, inset_y == y.
795         Inset * inset_hit = checkInsetHit(bv_->text, x, y);
796
797         if (bv_->theLockingInset()) {
798                 // We are in inset locking mode.
799
800                 /* LyX does a kind of work-area grabbing for insets.
801                    Only a ButtonPress Event outside the inset will 
802                    force a insetUnlock. */
803                 bv_->theLockingInset()->
804                         insetButtonRelease(bv_, x, y, button);
805                 return;
806         }
807         
808         selection_possible = false;
809         
810         if (button == 2)
811                 return;
812
813         // finish selection
814         if (button == 1) {
815                 workarea_.haveSelection(bv_->getLyXText()->selection.set());
816         }
817  
818         setState();
819         owner_->showState();
820         owner_->updateMenubar();
821         owner_->updateToolbar();
822
823         // Did we hit an editable inset?
824         if (inset_hit) {
825                 // Inset like error, notes and figures
826                 selection_possible = false;
827
828                 // if we reach this point with a selection, it
829                 // must mean we are currently selecting.
830                 // But we don't want to open the inset
831                 // because that is annoying for the user. 
832                 // So just pretend we didn't hit it.
833                 // this is OK because a "kosher" ButtonRelease
834                 // will follow a ButtonPress that clears
835                 // the selection.
836                 // Note this also fixes selection drawing
837                 // problems if we end up opening an inset
838                 if (bv_->getLyXText()->selection.set())
839                         return;
840  
841                 // CHECK fix this proper in 0.13
842                 // well, maybe 13.0 !!!!!!!!!
843
844                 // Following a ref shouldn't issue
845                 // a push on the undo-stack
846                 // anylonger, now that we have
847                 // keybindings for following
848                 // references and returning from
849                 // references.  IMHO though, it
850                 // should be the inset's own business
851                 // to push or not push on the undo
852                 // stack. They don't *have* to
853                 // alter the document...
854                 // (Joacim)
855                 // ...or maybe the SetCursorParUndo()
856                 // below isn't necessary at all anylonger?
857                 if (inset_hit->lyxCode() == Inset::REF_CODE) {
858                         setCursorParUndo(bv_);
859                 }
860
861                 owner_->message(inset_hit->editMessage());
862
863                 if (isHighlyEditableInset(inset_hit)) {
864                         // Highly editable inset, like math
865                         UpdatableInset *inset = (UpdatableInset *)inset_hit;
866                         inset->insetButtonRelease(bv_, x, y, button);
867                 } else {
868                         inset_hit->insetButtonRelease(bv_, x, y, button);
869                         inset_hit->edit(bv_, x, y, button);
870                 }
871                 return;
872         }
873
874         // Maybe we want to edit a bibitem ale970302
875         if (bv_->text->cursor.par()->bibkey && x < 20 + 
876             bibitemMaxWidth(bv_, textclasslist.
877                             TextClass(buffer_->
878                                       params.textclass).defaultfont())) {
879                 bv_->text->cursor.par()->bibkey->edit(bv_, 0, 0, 0);
880         }
881
882         return;
883 }
884
885
886 Box BufferView::Pimpl::insetDimensions(LyXText const & text,
887                                        LyXCursor const & cursor) const
888 {
889         Paragraph /*const*/ & par = *cursor.par();
890         pos_type const pos = cursor.pos();
891
892         lyx::Assert(par.getInset(pos));
893  
894         Inset const & inset(*par.getInset(pos));
895
896         LyXFont const & font = text.getFont(buffer_, &par, pos);
897  
898         int const width = inset.width(bv_, font);
899         int const inset_x = font.isVisibleRightToLeft()
900                 ? (cursor.x() - width) : cursor.x();
901  
902         return Box(
903                 inset_x + inset.scroll(),
904                 inset_x + width,
905                 cursor.y() - inset.ascent(bv_, font),
906                 cursor.y() + inset.descent(bv_, font));
907 }
908  
909  
910 Inset * BufferView::Pimpl::checkInset(LyXText const & text,
911                                       LyXCursor const & cursor,
912                                       int & x, int & y) const
913 {
914         pos_type const pos(cursor.pos());
915         Paragraph /*const*/ & par(*cursor.par());
916
917         if (pos >= par.size() || !par.isInset(pos)) {
918                 return 0;
919         }
920
921         Inset /*const*/ * inset = par.getInset(pos);
922  
923         if (!isEditableInset(inset)) {
924                 return 0;
925         }
926
927         Box b(insetDimensions(text, cursor));
928
929         if (!b.contained(x, y)) {
930                 lyxerr[Debug::GUI] << "Missed inset at x,y " << x << "," << y 
931                         << " box " << b << endl;
932                 return 0;
933         }
934  
935         text.setCursor(bv_, &par, pos, true);
936  
937         x -= b.x1;
938         // The origin of an inset is on the baseline
939         y -= (text.cursor.y());
940   
941         return inset;
942 }
943
944  
945 Inset * BufferView::Pimpl::checkInsetHit(LyXText * text, int & x, int & y)
946 {
947         if (!screen_.get())
948                 return 0;
949   
950         int y_tmp = y + text->first;
951  
952         LyXCursor cursor;
953         text->setCursorFromCoordinates(bv_, cursor, x, y_tmp);
954  
955         Inset * inset(checkInset(*text, cursor, x, y_tmp));
956
957         if (inset) {
958                 y = y_tmp;
959                 return inset;
960         }
961  
962         // look at previous position
963  
964         if (cursor.pos() == 0) {
965                 return 0;
966         }
967
968         // move back one
969         text->setCursor(bv_, cursor, cursor.par(), cursor.pos() - 1, true);
970
971         inset = checkInset(*text, cursor, x, y_tmp);
972         if (inset) {
973                 y = y_tmp;
974         }
975         return inset;
976 }
977
978
979 void BufferView::Pimpl::workAreaExpose()
980 {
981         static int work_area_width;
982         static unsigned int work_area_height;
983
984         bool const widthChange = workarea_.workWidth() != work_area_width;
985         bool const heightChange = workarea_.height() != work_area_height;
986
987         // update from work area
988         work_area_width = workarea_.workWidth();
989         work_area_height = workarea_.height();
990         if (buffer_ != 0) {
991                 if (widthChange) {
992                         // The visible LyXView need a resize
993                         owner_->resize();
994
995                         // Remove all texts from the textcache
996                         // This is not _really_ what we want to do. What
997                         // we really want to do is to delete in textcache
998                         // that does not have a BufferView with matching
999                         // width, but as long as we have only one BufferView
1000                         // deleting all gives the same result.
1001                         if (lyxerr.debugging())
1002                                 textcache.show(lyxerr, "Expose delete all");
1003                         textcache.clear();
1004                 } else if (heightChange) {
1005                         // Rebuild image of current screen
1006                         updateScreen();
1007                         // fitCursor() ensures we don't jump back
1008                         // to the start of the document on vertical
1009                         // resize
1010                         fitCursor();
1011
1012                         // The main window size has changed, repaint most stuff
1013                         redraw();
1014                 } else if (screen_.get())
1015                     screen_->redraw(bv_->text, bv_);
1016         } else {
1017                 // Grey box when we don't have a buffer
1018                 workarea_.greyOut();
1019         }
1020
1021         // always make sure that the scrollbar is sane.
1022         updateScrollbar();
1023         owner_->updateLayoutChoice();
1024         return;
1025 }
1026
1027
1028 void BufferView::Pimpl::update()
1029 {
1030         if (screen_.get() &&
1031                 (!bv_->theLockingInset() || !bv_->theLockingInset()->nodraw()))
1032         {
1033                 LyXText::text_status st = bv_->text->status();
1034                 screen_->update(bv_->text, bv_);
1035                 bool fitc = false;
1036                 while (bv_->text->status() == LyXText::CHANGED_IN_DRAW) {
1037                         if (bv_->text->fullRebreak(bv_)) {
1038                                 st = LyXText::NEED_MORE_REFRESH;
1039                                 bv_->text->setCursor(bv_, bv_->text->cursor.par(),
1040                                                                          bv_->text->cursor.pos());
1041                                 fitc = true;
1042                         }
1043                         bv_->text->status(bv_, st);
1044                         screen_->update(bv_->text, bv_);
1045                 }
1046                 // do this here instead of in the screen::update because of
1047                 // the above loop!
1048                 bv_->text->status(bv_, LyXText::UNCHANGED);
1049                 if (fitc)
1050                         fitCursor();
1051         }
1052 }
1053
1054 // Values used when calling update:
1055 // -3 - update
1056 // -2 - update, move sel_cursor if selection, fitcursor
1057 // -1 - update, move sel_cursor if selection, fitcursor, mark dirty
1058 //  0 - update, move sel_cursor if selection, fitcursor 
1059 //  1 - update, move sel_cursor if selection, fitcursor, mark dirty
1060 //  3 - update, move sel_cursor if selection
1061 //
1062 // update -
1063 // a simple redraw of the parts that need refresh
1064 //
1065 // move sel_cursor if selection -
1066 // the text's sel_cursor is moved if there is selection is progress
1067 //
1068 // fitcursor -
1069 // fitCursor() is called and the scrollbar updated
1070 //
1071 // mark dirty -
1072 // the buffer is marked dirty.
1073 //
1074 // enum {
1075 //       UPDATE = 0,
1076 //       SELECT = 1,
1077 //       FITCUR = 2,
1078 //       CHANGE = 4 
1079 // };
1080 //
1081 // UPDATE_ONLY = UPDATE;
1082 // UPDATE_SELECT = UPDATE | SELECT;
1083 // UPDATE_SELECT_MOVE = UPDATE | SELECT | FITCUR;
1084 // UPDATE_SELECT_MOVE_AFTER_CHANGE = UPDATE | SELECT | FITCUR | CHANGE;
1085 //
1086 // update(-3) -> update(0)         -> update(0) -> update(UPDATE)
1087 // update(-2) -> update(1 + 2)     -> update(3) -> update(SELECT|FITCUR)
1088 // update(-1) -> update(1 + 2 + 4) -> update(7) -> update(SELECT|FITCUR|CHANGE)
1089 // update(1)  -> update(1 + 2 + 4) -> update(7) -> update(SELECT|FITCUR|CHANGE)
1090 // update(3)  -> update(1)         -> update(1) -> update(SELECT)
1091
1092 void BufferView::Pimpl::update(LyXText * text, BufferView::UpdateCodes f)
1093 {
1094         owner_->updateLayoutChoice();
1095
1096         if (!text->selection.set() && (f & SELECT)) {
1097                 text->selection.cursor = text->cursor;
1098         }
1099
1100         text->fullRebreak(bv_);
1101
1102         if (text->inset_owner) {
1103                 text->inset_owner->setUpdateStatus(bv_, InsetText::NONE);
1104             updateInset(text->inset_owner, false);
1105         } else {
1106             update();
1107         }
1108                 
1109         if ((f & FITCUR)) {
1110                 fitCursor();
1111         }
1112
1113         if ((f & CHANGE)) {
1114                 buffer_->markDirty();
1115         }
1116 }
1117
1118
1119 // Callback for cursor timer
1120 void BufferView::Pimpl::cursorToggle()
1121 {
1122         // Quite a nice place for asyncron Inset updating, isn't it?
1123         // Actually no! This is run even if no buffer exist... so (Lgb)
1124         if (!buffer_) {
1125                 cursor_timeout.restart();
1126                 return;
1127         }
1128  
1129         int status = 1;
1130         int const pid = waitpid(static_cast<pid_t>(0), &status, WNOHANG);
1131         if (pid == -1) // error find out what is wrong
1132                 ; // ignore it for now.
1133         else if (pid > 0)
1134                 sigchldchecker(pid, &status);
1135
1136         updatelist.update(bv_);
1137         
1138         if (!screen_.get()) {
1139                 cursor_timeout.restart();
1140                 return;
1141         }
1142
1143         if (!bv_->theLockingInset()) {
1144                 screen_->cursorToggle(bv_);
1145         } else {
1146                 bv_->theLockingInset()->toggleInsetCursor(bv_);
1147         }
1148         
1149         cursor_timeout.restart();
1150 }
1151
1152
1153 void BufferView::Pimpl::cursorPrevious(LyXText * text)
1154 {
1155         if (!text->cursor.row()->previous())
1156                 return;
1157         
1158         int y = text->first;
1159         if (text->inset_owner)
1160                 y += bv_->text->first;
1161         Row * cursorrow = text->cursor.row();
1162         text->setCursorFromCoordinates(bv_, bv_->text->cursor.x_fix(), y);
1163         finishUndo();
1164         // This is to allow jumping over large insets
1165         if ((cursorrow == text->cursor.row()))
1166                 text->cursorUp(bv_);
1167         
1168         if (text->inset_owner ||
1169             text->cursor.row()->height() < workarea_.height())
1170                 screen_->draw(bv_->text, bv_,
1171                               text->cursor.y()
1172                               - text->cursor.row()->baseline()
1173                               + text->cursor.row()->height()
1174                               - workarea_.height() + 1);
1175         updateScrollbar();
1176 }
1177
1178
1179 void BufferView::Pimpl::cursorNext(LyXText * text)
1180 {
1181         if (!text->cursor.row()->next())
1182                 return;
1183         
1184         int y = text->first + workarea_.height();
1185 //      if (text->inset_owner)
1186 //              y += bv_->text->first;
1187         text->getRowNearY(y);
1188     
1189         Row * cursorrow = text->cursor.row();
1190         text->setCursorFromCoordinates(bv_, text->cursor.x_fix(), y); // + workarea_->height());
1191         finishUndo();
1192         // This is to allow jumping over large insets
1193         if ((cursorrow == bv_->text->cursor.row()))
1194                 text->cursorDown(bv_);
1195         
1196         if (text->inset_owner ||
1197             text->cursor.row()->height() < workarea_.height())
1198                 screen_->draw(bv_->text, bv_, text->cursor.y() -
1199                               text->cursor.row()->baseline());
1200         updateScrollbar();
1201 }
1202
1203
1204 bool BufferView::Pimpl::available() const
1205 {
1206         if (buffer_ && bv_->text) return true;
1207         return false;
1208 }
1209
1210
1211 void BufferView::Pimpl::beforeChange(LyXText * text)
1212 {
1213         toggleSelection();
1214         text->clearSelection();
1215 }
1216
1217
1218 void BufferView::Pimpl::savePosition(unsigned int i)
1219 {
1220         if (i >= saved_positions_num)
1221                 return;
1222         saved_positions[i] = Position(buffer_->fileName(),
1223                                       bv_->text->cursor.par()->id(),
1224                                       bv_->text->cursor.pos());
1225         if (i > 0) {
1226                 ostringstream str;
1227                 str << _("Saved bookmark") << ' ' << i;
1228                 owner_->message(str.str().c_str());
1229         }
1230 }
1231
1232
1233 void BufferView::Pimpl::restorePosition(unsigned int i)
1234 {
1235         if (i >= saved_positions_num)
1236                 return;
1237
1238         string const fname = saved_positions[i].filename;
1239
1240         beforeChange(bv_->text);
1241
1242         if (fname != buffer_->fileName()) {
1243                 Buffer * b = bufferlist.exists(fname) ?
1244                         bufferlist.getBuffer(fname) :
1245                         bufferlist.loadLyXFile(fname); // don't ask, just load it
1246                 if (b != 0) buffer(b);
1247         }
1248
1249         Paragraph * par = buffer_->getParFromID(saved_positions[i].par_id);
1250         if (!par)
1251                 return;
1252
1253         bv_->text->setCursor(bv_, par,
1254                              min(par->size(), saved_positions[i].par_pos));
1255
1256         update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
1257         if (i > 0) {
1258                 ostringstream str;
1259                 str << _("Moved to bookmark") << ' ' << i;
1260                 owner_->message(str.str().c_str());
1261         }
1262 }
1263
1264
1265 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
1266 {
1267         if (i >= saved_positions_num)
1268                 return false;
1269
1270         return !saved_positions[i].filename.empty();
1271 }
1272
1273
1274 void BufferView::Pimpl::setState()
1275 {
1276         if (!lyxrc.rtl_support)
1277                 return;
1278
1279         LyXText * text = bv_->getLyXText();
1280         if (text->real_current_font.isRightToLeft()) {
1281                 if (owner_->getIntl()->keymap == Intl::PRIMARY)
1282                         owner_->getIntl()->KeyMapSec();
1283         } else {
1284                 if (owner_->getIntl()->keymap == Intl::SECONDARY)
1285                         owner_->getIntl()->KeyMapPrim();
1286         }
1287 }
1288
1289
1290 void BufferView::Pimpl::insetSleep()
1291 {
1292         if (bv_->theLockingInset() && !inset_slept) {
1293                 bv_->theLockingInset()->getCursorPos(bv_, bv_->slx, bv_->sly);
1294                 bv_->theLockingInset()->insetUnlock(bv_);
1295                 inset_slept = true;
1296         }
1297 }
1298
1299
1300 void BufferView::Pimpl::insetWakeup()
1301 {
1302         if (bv_->theLockingInset() && inset_slept) {
1303                 bv_->theLockingInset()->edit(bv_, bv_->slx, bv_->sly, 0);
1304                 inset_slept = false;
1305         }
1306 }
1307
1308
1309 void BufferView::Pimpl::insetUnlock()
1310 {
1311         if (bv_->theLockingInset()) {
1312                 if (!inset_slept)
1313                         bv_->theLockingInset()->insetUnlock(bv_);
1314                 bv_->theLockingInset(0);
1315                 finishUndo();
1316                 inset_slept = false;
1317         }
1318 }
1319
1320
1321 bool BufferView::Pimpl::focus() const
1322 {
1323         return workarea_.hasFocus();
1324 }
1325
1326
1327 void BufferView::Pimpl::focus(bool f)
1328 {
1329         if (f) workarea_.setFocus();
1330 }
1331
1332
1333 bool BufferView::Pimpl::active() const
1334 {
1335         return workarea_.active();
1336 }
1337
1338
1339 bool BufferView::Pimpl::belowMouse() const 
1340 {
1341         return workarea_.belowMouse();
1342 }
1343
1344
1345 void BufferView::Pimpl::showCursor()
1346 {
1347         if (screen_.get()) {
1348                 if (bv_->theLockingInset())
1349                         bv_->theLockingInset()->showInsetCursor(bv_);
1350                 else
1351                         screen_->showCursor(bv_->text, bv_);
1352         }
1353 }
1354
1355
1356 void BufferView::Pimpl::hideCursor()
1357 {
1358         if (screen_.get()) {
1359                 if (!bv_->theLockingInset())
1360 //                      bv_->theLockingInset()->hideInsetCursor(bv_);
1361 //              else
1362                         screen_->hideCursor();
1363         }
1364 }
1365
1366
1367 void BufferView::Pimpl::toggleSelection(bool b)
1368 {
1369         if (screen_.get()) {
1370                 if (bv_->theLockingInset())
1371                         bv_->theLockingInset()->toggleSelection(bv_, b);
1372                 screen_->toggleSelection(bv_->text, bv_, b);
1373         }
1374 }
1375
1376
1377 void BufferView::Pimpl::toggleToggle()
1378 {
1379         if (screen_.get())
1380                 screen_->toggleToggle(bv_->text, bv_);
1381 }
1382
1383
1384 void BufferView::Pimpl::center() 
1385 {
1386         beforeChange(bv_->text);
1387         if (bv_->text->cursor.y() > static_cast<int>((workarea_.height() / 2))) {
1388                 screen_->draw(bv_->text, bv_, bv_->text->cursor.y() - workarea_.height() / 2);
1389         } else {
1390                 screen_->draw(bv_->text, bv_, 0);
1391         }
1392         update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
1393         redraw();
1394 }
1395
1396
1397 void BufferView::Pimpl::pasteClipboard(bool asPara) 
1398 {
1399         if (!buffer_) return;
1400
1401         screen_->hideCursor();
1402         beforeChange(bv_->text);
1403         
1404         string const clip(workarea_.getClipboard());
1405         
1406         if (clip.empty()) return;
1407
1408         if (asPara) {
1409                 bv_->getLyXText()->insertStringAsParagraphs(bv_, clip);
1410         } else {
1411                 bv_->getLyXText()->insertStringAsLines(bv_, clip);
1412         }
1413         update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
1414 }
1415
1416
1417 void BufferView::Pimpl::stuffClipboard(string const & stuff) const
1418 {
1419         workarea_.putClipboard(stuff);
1420 }
1421
1422
1423 /*
1424  * Dispatch functions for actions which can be valid for BufferView->text
1425  * and/or InsetText->text!!!
1426  */
1427
1428
1429 inline
1430 void BufferView::Pimpl::moveCursorUpdate(bool selecting)
1431 {
1432         LyXText * lt = bv_->getLyXText();
1433         
1434         if (selecting || lt->selection.mark()) {
1435                 lt->setSelection(bv_);
1436                 if (lt->bv_owner)
1437                         toggleToggle();
1438         }
1439         update(lt, BufferView::SELECT|BufferView::FITCUR);
1440         showCursor();
1441         
1442         /* ---> Everytime the cursor is moved, show the current font state. */
1443         // should this too me moved out of this func?
1444         //owner->showState();
1445         setState();
1446 }
1447
1448
1449 Inset * BufferView::Pimpl::getInsetByCode(Inset::Code code)
1450 {
1451         LyXCursor cursor = bv_->getLyXText()->cursor;
1452         Buffer::inset_iterator it =
1453                 find_if(Buffer::inset_iterator(
1454                         cursor.par(), cursor.pos()),
1455                         buffer_->inset_iterator_end(),
1456                         lyx::compare_memfun(&Inset::lyxCode, code));
1457         return it != buffer_->inset_iterator_end() ? (*it) : 0;
1458 }
1459
1460
1461 void BufferView::Pimpl::MenuInsertLyXFile(string const & filen)
1462 {
1463         string filename = filen;
1464
1465         if (filename.empty()) {
1466                 // Launch a file browser
1467                 string initpath = lyxrc.document_path;
1468
1469                 if (available()) {
1470                         string const trypath = owner_->buffer()->filePath();
1471                         // If directory is writeable, use this as default.
1472                         if (IsDirWriteable(trypath))
1473                                 initpath = trypath;
1474                 }
1475
1476                 FileDialog fileDlg(bv_->owner(),
1477                                    _("Select LyX document to insert"),
1478                         LFUN_FILE_INSERT,
1479                         make_pair(string(_("Documents|#o#O")),
1480                                   string(lyxrc.document_path)),
1481                         make_pair(string(_("Examples|#E#e")),
1482                                   string(AddPath(system_lyxdir, "examples"))));
1483
1484                 FileDialog::Result result =
1485                         fileDlg.Select(initpath,
1486                                        _("*.lyx| LyX Documents (*.lyx)"));
1487  
1488                 if (result.first == FileDialog::Later)
1489                         return;
1490
1491                 filename = result.second;
1492
1493                 // check selected filename
1494                 if (filename.empty()) {
1495                         owner_->message(_("Canceled."));
1496                         return;
1497                 }
1498         }
1499
1500         // get absolute path of file and add ".lyx" to the filename if
1501         // necessary
1502         filename = FileSearch(string(), filename, "lyx");
1503
1504         string const disp_fn(MakeDisplayPath(filename));
1505         
1506         ostringstream s1;
1507         s1 << _("Inserting document") << ' '
1508            << disp_fn << " ...";
1509         owner_->message(s1.str().c_str());
1510         bool const res = bv_->insertLyXFile(filename);
1511         if (res) {
1512                 ostringstream str;
1513                 str << _("Document") << ' ' << disp_fn
1514                     << ' ' << _("inserted.");
1515                 owner_->message(str.str().c_str());
1516         } else {
1517                 ostringstream str;
1518                 str << _("Could not insert document") << ' '
1519                     << disp_fn;
1520                 owner_->message(str.str().c_str());
1521         }
1522 }
1523
1524
1525 bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
1526 {
1527         lyxerr[Debug::ACTION] << "BufferView::Pimpl::Dispatch: action["
1528                               << action <<"] arg[" << argument << "]" << endl;
1529         
1530         switch (action) {
1531                 // --- Misc -------------------------------------------
1532         case LFUN_APPENDIX:
1533         {
1534                 if (available()) {
1535                         LyXText * lt = bv_->getLyXText();
1536                         lt->toggleAppendix(bv_);
1537                         update(lt,
1538                                BufferView::SELECT
1539                                | BufferView::FITCUR
1540                                | BufferView::CHANGE);
1541                 }
1542         }
1543         break;
1544
1545         case LFUN_TOC_INSERT:
1546         {
1547                 InsetCommandParams p;
1548                 p.setCmdName("tableofcontents");
1549                 Inset * inset = new InsetTOC(p);
1550                 if (!insertInset(inset, "Standard"))
1551                         delete inset;
1552                 break;
1553         }
1554                 
1555         case LFUN_TABULAR_FEATURE:
1556         case LFUN_SCROLL_INSET:
1557                 // this is not handled here as this funktion is only aktive
1558                 // if we have a locking_inset and that one is (or contains)
1559                 // a tabular-inset
1560                 break;
1561
1562         case LFUN_INSET_GRAPHICS:
1563         {
1564                 Inset * new_inset = new InsetGraphics;
1565                 if (!insertInset(new_inset)) {
1566                         delete new_inset;
1567                 } else {
1568                         // this is need because you don't use a inset->Edit()
1569                         updateInset(new_inset, true);
1570                         new_inset->edit(bv_);
1571                 }
1572                 break;
1573         }
1574                 
1575         case LFUN_PASTE:
1576                 bv_->paste();
1577                 setState();
1578                 break;
1579                 
1580         case LFUN_PASTESELECTION:
1581         {
1582                 bool asPara = false;
1583                 if (argument == "paragraph")
1584                         asPara = true;
1585                 pasteClipboard(asPara);
1586         }
1587         break;
1588         
1589         case LFUN_CUT:
1590                 bv_->cut();
1591                 break;
1592                 
1593         case LFUN_COPY:
1594                 bv_->copy();
1595                 break;
1596                 
1597         case LFUN_LAYOUT_COPY:
1598                 bv_->copyEnvironment();
1599                 break;
1600                 
1601         case LFUN_LAYOUT_PASTE:
1602                 bv_->pasteEnvironment();
1603                 setState();
1604                 break;
1605                 
1606         case LFUN_GOTOERROR:
1607                 gotoInset(Inset::ERROR_CODE, false);
1608                 break;
1609                 
1610         case LFUN_GOTONOTE:
1611                 gotoInset(Inset::IGNORE_CODE, false);
1612                 break;
1613
1614         case LFUN_REFERENCE_GOTO:
1615         {
1616                 vector<Inset::Code> tmp;
1617                 tmp.push_back(Inset::LABEL_CODE);
1618                 tmp.push_back(Inset::REF_CODE);
1619                 gotoInset(tmp, true);
1620                 break;
1621         }
1622
1623         case LFUN_HYPHENATION:
1624                 specialChar(InsetSpecialChar::HYPHENATION);
1625                 break;
1626                 
1627         case LFUN_LIGATURE_BREAK:
1628                 specialChar(InsetSpecialChar::LIGATURE_BREAK);
1629                 break;
1630                 
1631         case LFUN_LDOTS:
1632                 specialChar(InsetSpecialChar::LDOTS);
1633                 break;
1634                 
1635         case LFUN_END_OF_SENTENCE:
1636                 specialChar(InsetSpecialChar::END_OF_SENTENCE);
1637                 break;
1638
1639         case LFUN_MENU_SEPARATOR:
1640                 specialChar(InsetSpecialChar::MENU_SEPARATOR);
1641                 break;
1642                 
1643         case LFUN_HFILL:
1644                 hfill();
1645                 break;
1646                 
1647         case LFUN_DEPTH:
1648                 changeDepth(bv_, bv_->getLyXText(), 0);
1649                 break;
1650                 
1651         case LFUN_DEPTH_MIN:
1652                 changeDepth(bv_, bv_->getLyXText(), -1);
1653                 break;
1654                 
1655         case LFUN_DEPTH_PLUS:
1656                 changeDepth(bv_, bv_->getLyXText(), 1);
1657                 break;
1658                 
1659         case LFUN_FREE:
1660                 owner_->getDialogs()->setUserFreeFont();
1661                 break;
1662
1663         case LFUN_FILE_INSERT:
1664                 MenuInsertLyXFile(argument);
1665                 break;
1666         
1667         case LFUN_FILE_INSERT_ASCII_PARA:
1668                 InsertAsciiFile(bv_, argument, true);
1669                 break;
1670
1671         case LFUN_FILE_INSERT_ASCII:
1672                 InsertAsciiFile(bv_, argument, false);
1673                 break;
1674                 
1675         case LFUN_LAYOUT:
1676         {
1677                 lyxerr[Debug::INFO] << "LFUN_LAYOUT: (arg) "
1678                                     << argument << endl;
1679                 
1680                 // Derive layout number from given argument (string)
1681                 // and current buffer's textclass (number). */    
1682                 textclass_type tclass = buffer_->params.textclass;
1683                 pair <bool, layout_type> layout = 
1684                         textclasslist.NumberOfLayout(tclass, argument);
1685
1686                 // If the entry is obsolete, use the new one instead.
1687                 if (layout.first) {
1688                         string obs = textclasslist.Style(tclass, layout.second)
1689                                 .obsoleted_by();
1690                         if (!obs.empty()) 
1691                                 layout = textclasslist.NumberOfLayout(tclass, obs);
1692                 }
1693
1694                 // see if we found the layout number:
1695                 if (!layout.first) {
1696                         owner_->getLyXFunc()->setErrorMessage(
1697                                 string(N_("Layout ")) + argument +
1698                                 N_(" not known"));
1699                         break;
1700                 }
1701
1702                 if (current_layout != layout.second) {
1703                         LyXText * lt = bv_->getLyXText();
1704                         hideCursor();
1705                         current_layout = layout.second;
1706                         update(lt,
1707                                BufferView::SELECT
1708                                | BufferView::FITCUR);
1709                         lt->setLayout(bv_, layout.second);
1710                         owner_->setLayout(layout.second);
1711                         update(lt,
1712                                BufferView::SELECT
1713                                | BufferView::FITCUR
1714                                | BufferView::CHANGE);
1715                         setState();
1716                 }
1717         }
1718         break;
1719
1720         case LFUN_LANGUAGE:
1721                 lang(bv_, argument);
1722                 setState();
1723                 owner_->showState();
1724                 break;
1725
1726         case LFUN_EMPH:
1727                 emph(bv_);
1728                 owner_->showState();
1729                 break;
1730
1731         case LFUN_BOLD:
1732                 bold(bv_);
1733                 owner_->showState();
1734                 break;
1735                 
1736         case LFUN_NOUN:
1737                 noun(bv_);
1738                 owner_->showState();
1739                 break;
1740                 
1741         case LFUN_CODE:
1742                 code(bv_);
1743                 owner_->showState();
1744                 break;
1745                 
1746         case LFUN_SANS:
1747                 sans(bv_);
1748                 owner_->showState();
1749                 break;
1750                 
1751         case LFUN_ROMAN:
1752                 roman(bv_);
1753                 owner_->showState();
1754                 break;
1755                 
1756         case LFUN_DEFAULT:
1757                 styleReset(bv_);
1758                 owner_->showState();
1759                 break;
1760                 
1761         case LFUN_UNDERLINE:
1762                 underline(bv_);
1763                 owner_->showState();
1764                 break;
1765                 
1766         case LFUN_FONT_SIZE:
1767                 fontSize(bv_, argument);
1768                 owner_->showState();
1769                 break;
1770                 
1771         case LFUN_FONT_STATE:
1772                 owner_->getLyXFunc()->setMessage(currentState(bv_));
1773                 break;
1774                 
1775         case LFUN_UPCASE_WORD:
1776         {
1777                 LyXText * lt = bv_->getLyXText();
1778                 
1779                 update(lt,
1780                        BufferView::SELECT
1781                        | BufferView::FITCUR);
1782                 lt->changeCase(bv_, LyXText::text_uppercase);
1783                 if (lt->inset_owner)
1784                         updateInset(lt->inset_owner, true);
1785                 update(lt,
1786                        BufferView::SELECT
1787                        | BufferView::FITCUR
1788                        | BufferView::CHANGE);
1789         }
1790         break;
1791                 
1792         case LFUN_LOWCASE_WORD:
1793         {
1794                 LyXText * lt = bv_->getLyXText();
1795                 
1796                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1797                 lt->changeCase(bv_, LyXText::text_lowercase);
1798                 if (lt->inset_owner)
1799                         updateInset(lt->inset_owner, true);
1800                 update(lt,
1801                        BufferView::SELECT
1802                        | BufferView::FITCUR
1803                        | BufferView::CHANGE);
1804         }
1805         break;
1806                 
1807         case LFUN_CAPITALIZE_WORD:
1808         {
1809                 LyXText * lt = bv_->getLyXText();
1810                 
1811                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1812                 lt->changeCase(bv_, LyXText::text_capitalization);
1813                 if (lt->inset_owner)
1814                         updateInset(lt->inset_owner, true);
1815                 update(lt,
1816                        BufferView::SELECT
1817                        | BufferView::FITCUR
1818                        | BufferView::CHANGE);
1819         }
1820         break;
1821
1822         case LFUN_TRANSPOSE_CHARS:
1823         {
1824                 LyXText * lt = bv_->getLyXText();
1825                 
1826                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1827                 lt->transposeChars(*bv_);
1828                 if (lt->inset_owner)
1829                         updateInset(lt->inset_owner, true);
1830                 update(lt,
1831                        BufferView::SELECT
1832                        | BufferView::FITCUR
1833                        | BufferView::CHANGE);
1834         }
1835         break;
1836                 
1837                                           
1838         case LFUN_INSERT_LABEL:
1839                 MenuInsertLabel(bv_, argument);
1840                 break;
1841
1842         case LFUN_REF_INSERT:
1843                 if (argument.empty()) {
1844                         InsetCommandParams p("ref");
1845                         owner_->getDialogs()->createRef(p.getAsString());
1846                 } else {
1847                         InsetCommandParams p;
1848                         p.setFromString(argument);
1849
1850                         InsetRef * inset = new InsetRef(p, *buffer_);
1851                         if (!insertInset(inset))
1852                                 delete inset;
1853                         else
1854                                 updateInset(inset, true);
1855                 }
1856                 break;
1857
1858         case LFUN_BOOKMARK_SAVE:
1859                 savePosition(strToUnsignedInt(argument));
1860                 break;
1861
1862         case LFUN_BOOKMARK_GOTO:
1863                 restorePosition(strToUnsignedInt(argument));
1864                 break;
1865
1866         case LFUN_REF_GOTO:
1867         {
1868                 string label(argument);
1869                 if (label.empty()) {
1870                         InsetRef * inset = 
1871                                 static_cast<InsetRef*>(getInsetByCode(Inset::REF_CODE));
1872                         if (inset) {
1873                                 label = inset->getContents();
1874                                 savePosition(0);
1875                         }
1876                 }
1877                 
1878                 if (!label.empty()) {
1879                         //bv_->savePosition(0);
1880                         if (!bv_->gotoLabel(label))
1881                                 Alert::alert(_("Error"), 
1882                                            _("Couldn't find this label"), 
1883                                            _("in current document."));
1884                 }
1885         }
1886         break;
1887                 
1888                 // --- Cursor Movements -----------------------------
1889         case LFUN_RIGHT:
1890         {
1891                 LyXText * lt = bv_->getLyXText();
1892                 
1893                 bool is_rtl = lt->cursor.par()->isRightToLeftPar(buffer_->params);
1894                 if (!lt->selection.mark())
1895                         beforeChange(lt);
1896                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1897                 if (is_rtl)
1898                         lt->cursorLeft(bv_, false);
1899                 if (lt->cursor.pos() < lt->cursor.par()->size()
1900                     && lt->cursor.par()->isInset(lt->cursor.pos())
1901                     && isHighlyEditableInset(lt->cursor.par()->getInset(lt->cursor.pos()))) {
1902                         Inset * tmpinset = lt->cursor.par()->getInset(lt->cursor.pos());
1903                         owner_->getLyXFunc()->setMessage(tmpinset->editMessage());
1904                         if (is_rtl)
1905                                 tmpinset->edit(bv_, false);
1906                         else
1907                                 tmpinset->edit(bv_);
1908                         break;
1909                 }
1910                 if (!is_rtl)
1911                         lt->cursorRight(bv_, false);
1912                 finishUndo();
1913                 moveCursorUpdate(false);
1914                 owner_->showState();
1915         }
1916         break;
1917                 
1918         case LFUN_LEFT:
1919         {
1920                 // This is soooo ugly. Isn`t it possible to make
1921                 // it simpler? (Lgb)
1922                 LyXText * lt = bv_->getLyXText();
1923                 bool is_rtl = lt->cursor.par()->isRightToLeftPar(buffer_->params);
1924                 if (!lt->selection.mark())
1925                         beforeChange(lt);
1926                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1927                 LyXCursor const cur = lt->cursor;
1928                 if (!is_rtl)
1929                         lt->cursorLeft(bv_, false);
1930                 if ((is_rtl || cur != lt->cursor) && // only if really moved!
1931                     lt->cursor.pos() < lt->cursor.par()->size() &&
1932                     lt->cursor.par()->isInset(lt->cursor.pos()) &&
1933                     isHighlyEditableInset(lt->cursor.par()->getInset(lt->cursor.pos()))) {
1934                         Inset * tmpinset = lt->cursor.par()->getInset(lt->cursor.pos());
1935                         owner_->getLyXFunc()->setMessage(tmpinset->editMessage());
1936                         if (is_rtl)
1937                                 tmpinset->edit(bv_);
1938                         else
1939                                 tmpinset->edit(bv_, false);
1940                         break;
1941                 }
1942                 if  (is_rtl)
1943                         lt->cursorRight(bv_, false);
1944
1945                 finishUndo();
1946                 moveCursorUpdate(false);
1947                 owner_->showState();
1948         }
1949         break;
1950                 
1951         case LFUN_UP:
1952         {
1953                 LyXText * lt = bv_->getLyXText();
1954                 
1955                 if (!lt->selection.mark())
1956                         beforeChange(lt);
1957                 update(lt, BufferView::UPDATE);
1958                 lt->cursorUp(bv_);
1959                 finishUndo();
1960                 moveCursorUpdate(false);
1961                 owner_->showState();
1962         }
1963         break;
1964                 
1965         case LFUN_DOWN:
1966         {
1967                 LyXText * lt = bv_->getLyXText();
1968                 
1969                 if (!lt->selection.mark())
1970                         beforeChange(lt);
1971                 update(lt, BufferView::UPDATE);
1972                 lt->cursorDown(bv_);
1973                 finishUndo();
1974                 moveCursorUpdate(false);
1975                 owner_->showState();
1976         }
1977         break;
1978
1979         case LFUN_UP_PARAGRAPH:
1980         {
1981                 LyXText * lt = bv_->getLyXText();
1982                 
1983                 if (!lt->selection.mark())
1984                         beforeChange(lt);
1985                 update(lt, BufferView::UPDATE);
1986                 lt->cursorUpParagraph(bv_);
1987                 finishUndo();
1988                 moveCursorUpdate(false);
1989                 owner_->showState();
1990         }
1991         break;
1992                 
1993         case LFUN_DOWN_PARAGRAPH:
1994         {
1995                 LyXText * lt = bv_->getLyXText();
1996                 
1997                 if (!lt->selection.mark())
1998                         beforeChange(lt);
1999                 update(lt, BufferView::UPDATE);
2000                 lt->cursorDownParagraph(bv_);
2001                 finishUndo();
2002                 moveCursorUpdate(false);
2003                 owner_->showState();
2004         }
2005         break;
2006                 
2007         case LFUN_PRIOR:
2008         {
2009                 LyXText * lt = bv_->getLyXText();
2010                 
2011                 if (!lt->selection.mark())
2012                         beforeChange(lt);
2013                 update(lt, BufferView::UPDATE);
2014                 cursorPrevious(lt);
2015                 finishUndo();
2016                 moveCursorUpdate(false);
2017                 owner_->showState();
2018         }
2019         break;
2020                 
2021         case LFUN_NEXT:
2022         {
2023                 LyXText * lt = bv_->getLyXText();
2024                 
2025                 if (!lt->selection.mark())
2026                         beforeChange(lt);
2027                 update(lt, BufferView::UPDATE);
2028                 cursorNext(lt);
2029                 finishUndo();
2030                 moveCursorUpdate(false);
2031                 owner_->showState();
2032         }
2033         break;
2034                 
2035         case LFUN_HOME:
2036         {
2037                 LyXText * lt = bv_->getLyXText();
2038                 
2039                 if (!lt->selection.mark())
2040                         beforeChange(lt);
2041                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2042                 lt->cursorHome(bv_);
2043                 finishUndo();
2044                 moveCursorUpdate(false);
2045                 owner_->showState();
2046         }
2047         break;
2048                 
2049         case LFUN_END:
2050         {
2051                 LyXText * lt = bv_->getLyXText();
2052                 
2053                 if (!lt->selection.mark())
2054                         beforeChange(lt);
2055                 update(lt,
2056                        BufferView::SELECT|BufferView::FITCUR);
2057                 lt->cursorEnd(bv_);
2058                 finishUndo();
2059                 moveCursorUpdate(false);
2060                 owner_->showState();
2061         }
2062         break;
2063                 
2064         case LFUN_SHIFT_TAB:
2065         case LFUN_TAB:
2066         {
2067                 LyXText * lt = bv_->getLyXText();
2068                 
2069                 if (!lt->selection.mark())
2070                         beforeChange(lt);
2071                 update(lt,
2072                        BufferView::SELECT|BufferView::FITCUR);
2073                 lt->cursorTab(bv_);
2074                 finishUndo();
2075                 moveCursorUpdate(false);
2076                 owner_->showState();
2077         }
2078         break;
2079                 
2080         case LFUN_WORDRIGHT:
2081         {
2082                 LyXText * lt = bv_->getLyXText();
2083                 
2084                 if (!lt->selection.mark())
2085                         beforeChange(lt);
2086                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2087                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2088                         lt->cursorLeftOneWord(bv_);
2089                 else
2090                         lt->cursorRightOneWord(bv_);
2091                 finishUndo();
2092                 moveCursorUpdate(false);
2093                 owner_->showState();
2094         }
2095         break;
2096                 
2097         case LFUN_WORDLEFT:
2098         {
2099                 LyXText * lt = bv_->getLyXText();
2100                 
2101                 if (!lt->selection.mark())
2102                         beforeChange(lt);
2103                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2104                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2105                         lt->cursorRightOneWord(bv_);
2106                 else
2107                         lt->cursorLeftOneWord(bv_);
2108                 finishUndo();
2109                 moveCursorUpdate(false);
2110                 owner_->showState();
2111         }
2112         break;
2113                 
2114         case LFUN_BEGINNINGBUF:
2115         {
2116                 LyXText * lt = bv_->getLyXText();
2117                 
2118                 if (!lt->selection.mark())
2119                         beforeChange(lt);
2120                 update(lt,
2121                        BufferView::SELECT|BufferView::FITCUR);
2122                 lt->cursorTop(bv_);
2123                 finishUndo();
2124                 moveCursorUpdate(false);
2125                 owner_->showState();
2126         }
2127         break;
2128                 
2129         case LFUN_ENDBUF:
2130         {
2131                 LyXText * lt = bv_->getLyXText();
2132                 
2133                 if (!lt->selection.mark())
2134                         beforeChange(lt);
2135                 update(lt,
2136                        BufferView::SELECT|BufferView::FITCUR);
2137                 lt->cursorBottom(bv_);
2138                 finishUndo();
2139                 moveCursorUpdate(false);
2140                 owner_->showState();
2141         }
2142         break;
2143       
2144                 /* cursor selection ---------------------------- */
2145         case LFUN_RIGHTSEL:
2146         {
2147                 LyXText * lt = bv_->getLyXText();
2148                 
2149                 update(lt,
2150                        BufferView::SELECT|BufferView::FITCUR);
2151                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2152                         lt->cursorLeft(bv_);
2153                 else
2154                         lt->cursorRight(bv_);
2155                 finishUndo();
2156                 moveCursorUpdate(true);
2157                 owner_->showState();
2158         }
2159         break;
2160                 
2161         case LFUN_LEFTSEL:
2162         {
2163                 LyXText * lt = bv_->getLyXText();
2164                 
2165                 update(lt,
2166                        BufferView::SELECT|BufferView::FITCUR);
2167                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2168                         lt->cursorRight(bv_);
2169                 else
2170                         lt->cursorLeft(bv_);
2171                 finishUndo();
2172                 moveCursorUpdate(true);
2173                 owner_->showState();
2174         }
2175         break;
2176                 
2177         case LFUN_UPSEL:
2178         {
2179                 LyXText * lt = bv_->getLyXText();
2180                 
2181                 update(lt,
2182                        BufferView::SELECT|BufferView::FITCUR);
2183                 lt->cursorUp(bv_);
2184                 finishUndo();
2185                 moveCursorUpdate(true);
2186                 owner_->showState();
2187         }
2188         break;
2189                 
2190         case LFUN_DOWNSEL:
2191         {
2192                 LyXText * lt = bv_->getLyXText();
2193                 
2194                 update(lt,
2195                        BufferView::SELECT|BufferView::FITCUR);
2196                 lt->cursorDown(bv_);
2197                 finishUndo();
2198                 moveCursorUpdate(true);
2199                 owner_->showState();
2200         }
2201         break;
2202
2203         case LFUN_UP_PARAGRAPHSEL:
2204         {
2205                 LyXText * lt = bv_->getLyXText();
2206                 
2207                 update(lt,
2208                        BufferView::SELECT|BufferView::FITCUR);
2209                 lt->cursorUpParagraph(bv_);
2210                 finishUndo();
2211                 moveCursorUpdate(true);
2212                 owner_->showState();
2213         }
2214         break;
2215                 
2216         case LFUN_DOWN_PARAGRAPHSEL:
2217         {
2218                 LyXText * lt = bv_->getLyXText();
2219                 
2220                 update(lt,
2221                        BufferView::SELECT|BufferView::FITCUR);
2222                 lt->cursorDownParagraph(bv_);
2223                 finishUndo();
2224                 moveCursorUpdate(true);
2225                 owner_->showState();
2226         }
2227         break;
2228                 
2229         case LFUN_PRIORSEL:
2230         {
2231                 LyXText * lt = bv_->getLyXText();
2232                 
2233                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2234                 cursorPrevious(lt);
2235                 finishUndo();
2236                 moveCursorUpdate(true);
2237                 owner_->showState();
2238         }
2239         break;
2240                 
2241         case LFUN_NEXTSEL:
2242         {
2243                 LyXText * lt = bv_->getLyXText();
2244                 
2245                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2246                 cursorNext(lt);
2247                 finishUndo();
2248                 moveCursorUpdate(true);
2249                 owner_->showState();
2250         }
2251         break;
2252                 
2253         case LFUN_HOMESEL:
2254         {
2255                 LyXText * lt = bv_->getLyXText();
2256                 
2257                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2258                 lt->cursorHome(bv_);
2259                 finishUndo();
2260                 moveCursorUpdate(true);
2261                 owner_->showState();
2262         }
2263         break;
2264                 
2265         case LFUN_ENDSEL:
2266         {
2267                 LyXText * lt = bv_->getLyXText();
2268                 
2269                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2270                 lt->cursorEnd(bv_);
2271                 finishUndo();
2272                 moveCursorUpdate(true);
2273                 owner_->showState();
2274         }
2275         break;
2276                 
2277         case LFUN_WORDRIGHTSEL:
2278         {
2279                 LyXText * lt = bv_->getLyXText();
2280                 
2281                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2282                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2283                         lt->cursorLeftOneWord(bv_);
2284                 else
2285                         lt->cursorRightOneWord(bv_);
2286                 finishUndo();
2287                 moveCursorUpdate(true);
2288                 owner_->showState();
2289         }
2290         break;
2291                 
2292         case LFUN_WORDLEFTSEL:
2293         {
2294                 LyXText * lt = bv_->getLyXText();
2295                 
2296                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2297                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2298                         lt->cursorRightOneWord(bv_);
2299                 else
2300                         lt->cursorLeftOneWord(bv_);
2301                 finishUndo();
2302                 moveCursorUpdate(true);
2303                 owner_->showState();
2304         }
2305         break;
2306                 
2307         case LFUN_BEGINNINGBUFSEL:
2308         {
2309                 LyXText * lt = bv_->getLyXText();
2310                 
2311                 if (lt->inset_owner)
2312                         break;
2313                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2314                 lt->cursorTop(bv_);
2315                 finishUndo();
2316                 moveCursorUpdate(true);
2317                 owner_->showState();
2318         }
2319         break;
2320                 
2321         case LFUN_ENDBUFSEL:
2322         {
2323                 LyXText * lt = bv_->getLyXText();
2324                 
2325                 if (lt->inset_owner)
2326                         break;
2327                 update(lt,
2328                        BufferView::SELECT|BufferView::FITCUR);
2329                 lt->cursorBottom(bv_);
2330                 finishUndo();
2331                 moveCursorUpdate(true);
2332                 owner_->showState();
2333         }
2334         break;
2335
2336                 // --- text changing commands ------------------------
2337         case LFUN_BREAKLINE:
2338         {
2339                 LyXText * lt = bv_->getLyXText();
2340
2341                 beforeChange(lt);
2342                 lt->insertChar(bv_, Paragraph::META_NEWLINE);
2343                 update(lt,
2344                        BufferView::SELECT
2345                        | BufferView::FITCUR
2346                        | BufferView::CHANGE);
2347                 moveCursorUpdate(false);
2348         }
2349         break;
2350                 
2351         case LFUN_PROTECTEDSPACE:
2352         {
2353                 LyXText * lt = bv_->getLyXText();
2354
2355                 LyXLayout const & style = textclasslist
2356                         .Style(buffer_->params.textclass,
2357                                lt->cursor.par()->getLayout());
2358
2359                 if (style.free_spacing) {
2360                         lt->insertChar(bv_, ' ');
2361                         update(lt,
2362                                BufferView::SELECT
2363                                | BufferView::FITCUR
2364                                | BufferView::CHANGE);
2365                 } else {
2366                         protectedBlank(lt);
2367                 }
2368                 moveCursorUpdate(false);
2369         }
2370         break;
2371                 
2372         case LFUN_SETMARK:
2373         {
2374                 LyXText * lt = bv_->getLyXText();
2375
2376                 if (lt->selection.mark()) {
2377                         beforeChange(lt);
2378                         update(lt,
2379                                BufferView::SELECT
2380                                | BufferView::FITCUR);
2381                         owner_->getLyXFunc()->setMessage(N_("Mark removed"));
2382                 } else {
2383                         beforeChange(lt);
2384                         lt->selection.mark(true);
2385                         update(lt,
2386                                BufferView::SELECT
2387                                | BufferView::FITCUR);
2388                         owner_->getLyXFunc()->setMessage(N_("Mark set"));
2389                 }
2390                 lt->selection.cursor = lt->cursor;
2391         }
2392         break;
2393                 
2394         case LFUN_DELETE:
2395         {
2396                 LyXText * lt = bv_->getLyXText();
2397
2398                 if (!lt->selection.set()) {
2399                         lt->Delete(bv_);
2400                         lt->selection.cursor = lt->cursor;
2401                         update(lt,
2402                                BufferView::SELECT
2403                                | BufferView::FITCUR
2404                                | BufferView::CHANGE);
2405                         // It is possible to make it a lot faster still
2406                         // just comment out the line below...
2407                         showCursor();
2408                 } else {
2409                         bv_->cut(false);
2410                 }
2411                 moveCursorUpdate(false);
2412                 owner_->showState();
2413                 setState();
2414         }
2415         break;
2416
2417         case LFUN_DELETE_SKIP:
2418         {
2419                 LyXText * lt = bv_->getLyXText();
2420
2421                 // Reverse the effect of LFUN_BREAKPARAGRAPH_SKIP.
2422                 
2423                 LyXCursor cursor = lt->cursor;
2424
2425                 if (!lt->selection.set()) {
2426                         if (cursor.pos() == cursor.par()->size()) {
2427                                 lt->cursorRight(bv_);
2428                                 cursor = lt->cursor;
2429                                 if (cursor.pos() == 0
2430                                     && !(cursor.par()->params().spaceTop()
2431                                          == VSpace (VSpace::NONE))) {
2432                                         lt->setParagraph
2433                                                 (bv_,
2434                                                  cursor.par()->params().lineTop(),
2435                                                  cursor.par()->params().lineBottom(),
2436                                                  cursor.par()->params().pagebreakTop(), 
2437                                                  cursor.par()->params().pagebreakBottom(),
2438                                                  VSpace(VSpace::NONE), 
2439                                                  cursor.par()->params().spaceBottom(),
2440                                                  cursor.par()->params().spacing(), 
2441                                                  cursor.par()->params().align(), 
2442                                                  cursor.par()->params().labelWidthString(), 0);
2443                                         lt->cursorLeft(bv_);
2444                                         update(lt, 
2445                                                BufferView::SELECT
2446                                                | BufferView::FITCUR
2447                                                | BufferView::CHANGE);
2448                                 } else {
2449                                         lt->cursorLeft(bv_);
2450                                         lt->Delete(bv_);
2451                                         lt->selection.cursor = lt->cursor;
2452                                         update(lt,
2453                                                BufferView::SELECT
2454                                                | BufferView::FITCUR
2455                                                | BufferView::CHANGE);
2456                                 }
2457                         } else {
2458                                 lt->Delete(bv_);
2459                                 lt->selection.cursor = lt->cursor;
2460                                 update(lt,
2461                                        BufferView::SELECT
2462                                        | BufferView::FITCUR
2463                                        | BufferView::CHANGE);
2464                         }
2465                 } else {
2466                         bv_->cut(false);
2467                 }
2468         }
2469         break;
2470
2471         /* -------> Delete word forward. */
2472         case LFUN_DELETE_WORD_FORWARD:
2473                 update(bv_->getLyXText(), BufferView::SELECT|BufferView::FITCUR);
2474                 bv_->getLyXText()->deleteWordForward(bv_);
2475                 update(bv_->getLyXText(), BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2476                 moveCursorUpdate(false);
2477                 owner_->showState();
2478                 break;
2479
2480                 /* -------> Delete word backward. */
2481         case LFUN_DELETE_WORD_BACKWARD:
2482         {
2483                 LyXText * lt = bv_->getLyXText();
2484                 
2485                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2486                 lt->deleteWordBackward(bv_);
2487                 update(lt,
2488                        BufferView::SELECT
2489                        | BufferView::FITCUR
2490                        | BufferView::CHANGE);
2491                 moveCursorUpdate(false);
2492                 owner_->showState();
2493         }
2494         break;
2495                 
2496                 /* -------> Kill to end of line. */
2497         case LFUN_DELETE_LINE_FORWARD:
2498         {
2499                 LyXText * lt = bv_->getLyXText();
2500                 
2501                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2502                 lt->deleteLineForward(bv_);
2503                 update(lt,
2504                        BufferView::SELECT
2505                        | BufferView::FITCUR
2506                        | BufferView::CHANGE);
2507                 moveCursorUpdate(false);
2508         }
2509         break;
2510                 
2511                 /* -------> Set mark off. */
2512         case LFUN_MARK_OFF:
2513         {
2514                 LyXText * lt = bv_->getLyXText();
2515                 
2516                 beforeChange(lt);
2517                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2518                 lt->selection.cursor = lt->cursor;
2519                 owner_->getLyXFunc()->setMessage(N_("Mark off"));
2520         }
2521         break;
2522
2523                 /* -------> Set mark on. */
2524         case LFUN_MARK_ON:
2525         {
2526                 LyXText * lt = bv_->getLyXText();
2527                 
2528                 beforeChange(lt);
2529                 lt->selection.mark(true);
2530                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2531                 lt->selection.cursor = lt->cursor;
2532                 owner_->getLyXFunc()->setMessage(N_("Mark on"));
2533         }
2534         break;
2535                 
2536         case LFUN_BACKSPACE:
2537         {
2538                 LyXText * lt = bv_->getLyXText();
2539                 
2540                 if (!lt->selection.set()) {
2541                         if (owner_->getIntl()->getTrans().backspace()) {
2542                                 lt->backspace(bv_);
2543                                 lt->selection.cursor = lt->cursor;
2544                                 update(lt,
2545                                        BufferView::SELECT
2546                                        | BufferView::FITCUR
2547                                        | BufferView::CHANGE);
2548                                 // It is possible to make it a lot faster still
2549                                 // just comment out the line below...
2550                                 showCursor();
2551                         }
2552                 } else {
2553                         bv_->cut(false);
2554                 }
2555                 owner_->showState();
2556                 setState();
2557         }
2558         break;
2559
2560         case LFUN_BACKSPACE_SKIP:
2561         {
2562                 // Reverse the effect of LFUN_BREAKPARAGRAPH_SKIP.
2563                 LyXText * lt = bv_->getLyXText();
2564                 
2565                 LyXCursor cursor = lt->cursor;
2566                 
2567                 if (!lt->selection.set()) {
2568                         if (cursor.pos() == 0 
2569                             && !(cursor.par()->params().spaceTop() 
2570                                  == VSpace (VSpace::NONE))) {
2571                                 lt->setParagraph 
2572                                         (bv_,
2573                                          cursor.par()->params().lineTop(),      
2574                                          cursor.par()->params().lineBottom(),
2575                                          cursor.par()->params().pagebreakTop(), 
2576                                          cursor.par()->params().pagebreakBottom(),
2577                                          VSpace(VSpace::NONE), cursor.par()->params().spaceBottom(),
2578                                          cursor.par()->params().spacing(), 
2579                                          cursor.par()->params().align(), 
2580                                          cursor.par()->params().labelWidthString(), 0);
2581                                 update(lt,
2582                                        BufferView::SELECT
2583                                        | BufferView::FITCUR
2584                                        | BufferView::CHANGE);
2585                         } else {
2586                                 lt->backspace(bv_);
2587                                 lt->selection.cursor = cursor;
2588                                 update(lt,
2589                                        BufferView::SELECT
2590                                        | BufferView::FITCUR
2591                                        | BufferView::CHANGE);
2592                         }
2593                 } else
2594                         bv_->cut(false);
2595         }
2596         break;
2597
2598         case LFUN_BREAKPARAGRAPH:
2599         {
2600                 LyXText * lt = bv_->getLyXText();
2601                 
2602                 beforeChange(lt);
2603                 lt->breakParagraph(bv_, 0);
2604                 update(lt,
2605                        BufferView::SELECT
2606                        | BufferView::FITCUR
2607                        | BufferView::CHANGE);
2608                 lt->selection.cursor = lt->cursor;
2609                 setState();
2610                 owner_->showState();
2611                 break;
2612         }
2613
2614         case LFUN_BREAKPARAGRAPHKEEPLAYOUT:
2615         {
2616                 LyXText * lt = bv_->getLyXText();
2617                 
2618                 beforeChange(lt);
2619                 lt->breakParagraph(bv_, 1);
2620                 update(lt,
2621                        BufferView::SELECT
2622                        | BufferView::FITCUR
2623                        | BufferView::CHANGE);
2624                 lt->selection.cursor = lt->cursor;
2625                 setState();
2626                 owner_->showState();
2627                 break;
2628         }
2629         
2630         case LFUN_BREAKPARAGRAPH_SKIP:
2631         {
2632                 // When at the beginning of a paragraph, remove
2633                 // indentation and add a "defskip" at the top.
2634                 // Otherwise, do the same as LFUN_BREAKPARAGRAPH.
2635                 LyXText * lt = bv_->getLyXText();
2636                 
2637                 LyXCursor cursor = lt->cursor;
2638                 
2639                 beforeChange(lt);
2640                 if (cursor.pos() == 0) {
2641                         if (cursor.par()->params().spaceTop() == VSpace(VSpace::NONE)) {
2642                                 lt->setParagraph
2643                                         (bv_,
2644                                          cursor.par()->params().lineTop(),
2645                                          cursor.par()->params().lineBottom(),
2646                                          cursor.par()->params().pagebreakTop(),
2647                                          cursor.par()->params().pagebreakBottom(),
2648                                          VSpace(VSpace::DEFSKIP), cursor.par()->params().spaceBottom(),
2649                                          cursor.par()->params().spacing(),
2650                                          cursor.par()->params().align(),
2651                                          cursor.par()->params().labelWidthString(), 1);
2652                                 //update(BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2653                         } 
2654                 }
2655                 else {
2656                         lt->breakParagraph(bv_, 0);
2657                         //update(BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2658                 }
2659
2660                 update(lt,
2661                        BufferView::SELECT
2662                        | BufferView::FITCUR
2663                        | BufferView::CHANGE);
2664                 lt->selection.cursor = cursor;
2665                 setState();
2666                 owner_->showState();
2667         }
2668         break;
2669
2670         case LFUN_PARAGRAPH_SPACING:
2671         {
2672                 LyXText * lt = bv_->getLyXText();
2673                 
2674                 Paragraph * par = lt->cursor.par();
2675                 Spacing::Space cur_spacing = par->params().spacing().getSpace();
2676                 float cur_value = 1.0;
2677                 if (cur_spacing == Spacing::Other) {
2678                         cur_value = par->params().spacing().getValue();
2679                 }
2680                 
2681                 istringstream istr(argument.c_str());
2682
2683                 string tmp;
2684                 istr >> tmp;
2685                 Spacing::Space new_spacing = cur_spacing;
2686                 float new_value = cur_value;
2687                 if (tmp.empty()) {
2688                         lyxerr << "Missing argument to `paragraph-spacing'"
2689                                << endl;
2690                 } else if (tmp == "single") {
2691                         new_spacing = Spacing::Single;
2692                 } else if (tmp == "onehalf") {
2693                         new_spacing = Spacing::Onehalf;
2694                 } else if (tmp == "double") {
2695                         new_spacing = Spacing::Double;
2696                 } else if (tmp == "other") {
2697                         new_spacing = Spacing::Other;
2698                         float tmpval = 0.0;
2699                         istr >> tmpval;
2700                         lyxerr << "new_value = " << tmpval << endl;
2701                         if (tmpval != 0.0)
2702                                 new_value = tmpval;
2703                 } else if (tmp == "default") {
2704                         new_spacing = Spacing::Default;
2705                 } else {
2706                         lyxerr << _("Unknown spacing argument: ")
2707                                << argument << endl;
2708                 }
2709                 if (cur_spacing != new_spacing || cur_value != new_value) {
2710                         par->params().spacing(Spacing(new_spacing, new_value));
2711                         lt->redoParagraph(bv_);
2712                         update(lt,
2713                                BufferView::SELECT
2714                                | BufferView::FITCUR
2715                                | BufferView::CHANGE);
2716                 }
2717         }
2718         break;
2719         
2720         case LFUN_INSET_TOGGLE:
2721         {
2722                 LyXText * lt = bv_->getLyXText();
2723                 hideCursor();
2724                 beforeChange(lt);
2725                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2726                 lt->toggleInset(bv_);
2727                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2728                 setState();
2729         }       
2730                 break;
2731
2732         case LFUN_QUOTE:
2733                 smartQuote();
2734                 break;
2735
2736         case LFUN_HTMLURL:
2737         case LFUN_URL:
2738         {
2739                 InsetCommandParams p;
2740                 if (action == LFUN_HTMLURL)
2741                         p.setCmdName("htmlurl");
2742                 else
2743                         p.setCmdName("url");
2744                 owner_->getDialogs()->createUrl(p.getAsString());
2745         }
2746         break;
2747         
2748         case LFUN_INSERT_URL:
2749         {
2750                 InsetCommandParams p;
2751                 p.setFromString(argument);
2752
2753                 InsetUrl * inset = new InsetUrl(p);
2754                 if (!insertInset(inset))
2755                         delete inset;
2756                 else
2757                         updateInset(inset, true);
2758         }
2759         break;
2760         
2761         case LFUN_INSET_TEXT:
2762                 insertAndEditInset(new InsetText);
2763                 break;
2764         
2765         case LFUN_INSET_ERT:
2766                 insertAndEditInset(new InsetERT);
2767                 break;
2768         
2769         case LFUN_INSET_EXTERNAL:
2770                 insertAndEditInset(new InsetExternal);
2771                 break;
2772         
2773         case LFUN_INSET_FOOTNOTE:
2774                 insertAndEditInset(new InsetFoot);
2775                 break;
2776
2777         case LFUN_INSET_MARGINAL:
2778                 insertAndEditInset(new InsetMarginal);
2779                 break;
2780
2781         case LFUN_INSET_MINIPAGE:
2782                 insertAndEditInset(new InsetMinipage);
2783                 break;
2784
2785         case LFUN_INSERT_NOTE:
2786                 insertAndEditInset(new InsetNote);
2787                 break;
2788
2789         case LFUN_INSET_FLOAT:
2790                 // check if the float type exist
2791                 if (floatList.typeExist(argument)) {
2792                         insertAndEditInset(new InsetFloat(argument));
2793                 } else {
2794                         lyxerr << "Non-existent float type: "
2795                                << argument << endl;
2796                 }
2797                 break;
2798
2799         case LFUN_INSET_WIDE_FLOAT:
2800         {
2801                 // check if the float type exist
2802                 if (floatList.typeExist(argument)) {
2803                         InsetFloat * new_inset = new InsetFloat(argument);
2804                         new_inset->wide(true);
2805                         if (insertInset(new_inset))
2806                                 new_inset->edit(bv_);
2807                         else
2808                                 delete new_inset;
2809                 } else {
2810                         lyxerr << "Non-existent float type: "
2811                                << argument << endl;
2812                 }
2813                 
2814         }
2815         break;
2816
2817 #if 0
2818         case LFUN_INSET_LIST:
2819                 insertAndEditInset(new InsetList);
2820                 break;
2821
2822         case LFUN_INSET_THEOREM:
2823                 insertAndEditInset(new InsetTheorem);
2824                 break;
2825 #endif
2826                 
2827         case LFUN_INSET_CAPTION:
2828         {
2829                 // Do we have a locking inset...
2830                 if (bv_->theLockingInset()) {
2831                         lyxerr << "Locking inset code: "
2832                                << static_cast<int>(bv_->theLockingInset()->lyxCode());
2833                         InsetCaption * new_inset = new InsetCaption;
2834                         new_inset->setOwner(bv_->theLockingInset());
2835                         new_inset->setAutoBreakRows(true);
2836                         new_inset->setDrawFrame(0, InsetText::LOCKED);
2837                         new_inset->setFrameColor(0, LColor::captionframe);
2838                         if (insertInset(new_inset))
2839                                 new_inset->edit(bv_);
2840                         else
2841                                 delete new_inset;
2842                 }
2843         }
2844         break;
2845         
2846         case LFUN_INSET_TABULAR:
2847         {
2848                 int r = 2;
2849                 int c = 2;
2850                 if (!argument.empty())
2851                         ::sscanf(argument.c_str(),"%d%d", &r, &c);
2852                 InsetTabular * new_inset =
2853                         new InsetTabular(*buffer_, r, c);
2854                 bool const rtl =
2855                         bv_->getLyXText()->real_current_font.isRightToLeft();
2856                 if (!open_new_inset(new_inset, rtl))
2857                         delete new_inset;
2858         }
2859         break;
2860
2861         // --- lyxserver commands ----------------------------
2862
2863         case LFUN_CHARATCURSOR:
2864         {
2865                 pos_type pos = bv_->getLyXText()->cursor.pos();
2866                 if (pos < bv_->getLyXText()->cursor.par()->size())
2867                         owner_->getLyXFunc()->setMessage(
2868                                 tostr(bv_->getLyXText()->cursor.par()->getChar(pos)));
2869                 else
2870                         owner_->getLyXFunc()->setMessage("EOF");
2871         }
2872         break;
2873         
2874         case LFUN_GETXY:
2875                 owner_->getLyXFunc()->setMessage(tostr(bv_->getLyXText()->cursor.x())
2876                                                  + ' '
2877                                                  + tostr(bv_->getLyXText()->cursor.y()));
2878                 break;
2879                 
2880         case LFUN_SETXY:
2881         {
2882                 int x = 0;
2883                 int y = 0;
2884                 if (::sscanf(argument.c_str(), " %d %d", &x, &y) != 2) {
2885                         lyxerr << "SETXY: Could not parse coordinates in '"
2886                                << argument << std::endl;
2887                 }
2888                 bv_->getLyXText()->setCursorFromCoordinates(bv_, x, y);
2889         }
2890         break;
2891         
2892         case LFUN_GETLAYOUT:
2893                 owner_->getLyXFunc()->setMessage(tostr(bv_->getLyXText()->cursor.par()->layout));
2894                 break;
2895                         
2896         case LFUN_GETFONT:
2897         {
2898                 LyXFont & font = bv_->getLyXText()->current_font;
2899                 if (font.shape() == LyXFont::ITALIC_SHAPE)
2900                         owner_->getLyXFunc()->setMessage("E");
2901                 else if (font.shape() == LyXFont::SMALLCAPS_SHAPE)
2902                         owner_->getLyXFunc()->setMessage("N");
2903                 else
2904                         owner_->getLyXFunc()->setMessage("0");
2905
2906         }
2907         break;
2908
2909         // --- accented characters ---------------------------
2910                 
2911         case LFUN_UMLAUT:
2912         case LFUN_CIRCUMFLEX:
2913         case LFUN_GRAVE:
2914         case LFUN_ACUTE:
2915         case LFUN_TILDE:
2916         case LFUN_CEDILLA:
2917         case LFUN_MACRON:
2918         case LFUN_DOT:
2919         case LFUN_UNDERDOT:
2920         case LFUN_UNDERBAR:
2921         case LFUN_CARON:
2922         case LFUN_SPECIAL_CARON:
2923         case LFUN_BREVE:
2924         case LFUN_TIE:
2925         case LFUN_HUNG_UMLAUT:
2926         case LFUN_CIRCLE:
2927         case LFUN_OGONEK:
2928                 if (argument.empty()) {
2929                         // As always...
2930                         owner_->getLyXFunc()->handleKeyFunc(action);
2931                 } else {
2932                         owner_->getLyXFunc()->handleKeyFunc(action);
2933                         owner_->getIntl()->getTrans()
2934                                 .TranslateAndInsert(argument[0], bv_->getLyXText());
2935                         update(bv_->getLyXText(),
2936                                BufferView::SELECT
2937                                | BufferView::FITCUR
2938                                | BufferView::CHANGE);
2939                 }
2940                 break;
2941         
2942         case LFUN_MATH_MACRO:
2943                 mathDispatchMathMacro(bv_, argument);
2944                 break;
2945
2946         case LFUN_MATH_DELIM:     
2947                 mathDispatchMathDelim(bv_, argument);
2948                 break;
2949
2950         case LFUN_INSERT_MATRIX:
2951                 mathDispatchInsertMatrix(bv_, argument);
2952                 break;
2953
2954         case LFUN_INSERT_MATH:
2955                 mathDispatchInsertMath(bv_, argument);
2956                 break;
2957
2958         case LFUN_MATH_IMPORT_SELECTION: // Imports LaTeX from the X selection
2959                 mathDispatchMathImportSelection(bv_, argument);
2960                 break;
2961
2962         case LFUN_MATH_DISPLAY:          // Open or create a displayed math inset
2963                 mathDispatchMathDisplay(bv_, argument);
2964                 break;
2965
2966         case LFUN_MATH_MODE:             // Open or create an inlined math inset 
2967                 mathDispatchMathMode(bv_, argument);
2968                 break;
2969                 
2970         case LFUN_GREEK:                 // Insert a single greek letter
2971                 mathDispatchGreek(bv_, argument);
2972                 break;
2973                 
2974         case LFUN_CITATION_INSERT:
2975         {
2976                 InsetCommandParams p;
2977                 p.setFromString(argument);
2978
2979                 InsetCitation * inset = new InsetCitation(p);
2980                 if (!insertInset(inset))
2981                         delete inset;
2982                 else
2983                         updateInset(inset, true);
2984         }
2985         break;
2986                     
2987         case LFUN_INSERT_BIBTEX:
2988         {   
2989                 // ale970405+lasgoutt970425
2990                 // The argument can be up to two tokens separated 
2991                 // by a space. The first one is the bibstyle.
2992                 string const db       = token(argument, ' ', 0);
2993                 string const bibstyle = token(argument, ' ', 1);
2994
2995                 InsetCommandParams p("BibTeX", db, bibstyle);
2996                 InsetBibtex * inset = new InsetBibtex(p);
2997                 
2998                 if (insertInset(inset)) {
2999                         if (argument.empty())
3000                                 inset->edit(bv_);
3001                 } else
3002                         delete inset;
3003         }
3004         break;
3005                 
3006         // BibTeX data bases
3007         case LFUN_BIBDB_ADD:
3008         {
3009                 InsetBibtex * inset = 
3010                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
3011                 if (inset) {
3012                         inset->addDatabase(argument);
3013                 }
3014         }
3015         break;
3016                     
3017         case LFUN_BIBDB_DEL:
3018         {
3019                 InsetBibtex * inset = 
3020                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
3021                 if (inset) {
3022                         inset->delDatabase(argument);
3023                 }
3024         }
3025         break;
3026         
3027         case LFUN_BIBTEX_STYLE:
3028         {
3029                 InsetBibtex * inset = 
3030                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
3031                 if (inset) {
3032                         inset->setOptions(argument);
3033                 }
3034         }
3035         break;
3036                 
3037         case LFUN_INDEX_CREATE:
3038         {
3039                 InsetCommandParams p("index");
3040                 if (argument.empty()) {
3041                         string const idxstring(bv_->getLyXText()->getStringToIndex(bv_));
3042                         p.setContents(idxstring);
3043                 } else {
3044                         p.setContents(argument);
3045                 }
3046
3047                 owner_->getDialogs()->createIndex(p.getAsString());
3048         }
3049         break;
3050                     
3051         case LFUN_INDEX_INSERT:
3052         {
3053                 InsetCommandParams p;
3054                 p.setFromString(argument);
3055                 InsetIndex * inset = new InsetIndex(p);
3056
3057                 if (!insertInset(inset))
3058                         delete inset;
3059                 else
3060                         updateInset(inset, true);
3061         }
3062         break;
3063                     
3064         case LFUN_INDEX_INSERT_LAST:
3065         {
3066                 string const idxstring(bv_->getLyXText()->getStringToIndex(bv_));
3067                 if (!idxstring.empty()) {
3068                         owner_->message(_("Word `")
3069                                         + idxstring + _(("' indexed.")));
3070                         InsetCommandParams p("index", idxstring);
3071                         InsetIndex * inset = new InsetIndex(p);
3072                         
3073                         if (!insertInset(inset))
3074                                 delete inset;
3075                         else
3076                                 updateInset(inset, true);
3077                 }
3078         }
3079         break;
3080
3081         case LFUN_INDEX_PRINT:
3082         {
3083                 InsetCommandParams p("printindex");
3084                 Inset * inset = new InsetPrintIndex(p);
3085                 if (!insertInset(inset, "Standard"))
3086                         delete inset;
3087         }
3088         break;
3089
3090         case LFUN_PARENTINSERT:
3091         {
3092                 lyxerr << "arg " << argument << endl;
3093                 InsetCommandParams p("lyxparent", argument);
3094                 Inset * inset = new InsetParent(p, *buffer_);
3095                 if (!insertInset(inset, "Standard"))
3096                         delete inset;
3097         }
3098                  
3099         break;
3100
3101         case LFUN_CHILD_INSERT:
3102         {
3103                 InsetInclude::Params p;
3104                 p.cparams.setFromString(argument);
3105                 p.masterFilename_ = buffer_->fileName();
3106
3107                 InsetInclude * inset = new InsetInclude(p);
3108                 if (!insertInset(inset))
3109                         delete inset;
3110                 else {
3111                         updateInset(inset, true);
3112                         bv_->owner()->getDialogs()->showInclude(inset);
3113                 }
3114         }
3115         break; 
3116
3117         case LFUN_FLOAT_LIST:
3118         {
3119                 // We should check the argument for validity. (Lgb)
3120                 Inset * inset = new InsetFloatList(argument);
3121                 if (!insertInset(inset, "Standard"))
3122                         delete inset;
3123         }
3124         break;
3125         
3126         case LFUN_THESAURUS_ENTRY:
3127         {
3128                 string arg = argument;
3129
3130                 if (arg.empty()) {
3131                         arg = bv_->getLyXText()->selectionAsString(buffer_,
3132                                                                    false);
3133  
3134                         // FIXME
3135                         if (arg.size() > 100 || arg.empty()) {
3136                                 // Get word or selection
3137                                 bv_->getLyXText()->selectWordWhenUnderCursor(bv_, LyXText::WHOLE_WORD);
3138                                 arg = bv_->getLyXText()->selectionAsString(buffer_, false);
3139                                 // FIXME: where is getLyXText()->unselect(bv_) ?
3140                         }
3141                 }
3142
3143                 bv_->owner()->getDialogs()->showThesaurus(arg);
3144         }
3145                 break;
3146  
3147         case LFUN_SELFINSERT:
3148         {
3149                 if (argument.empty()) break;
3150                 
3151                 /* Automatically delete the currently selected
3152                  * text and replace it with what is being
3153                  * typed in now. Depends on lyxrc settings
3154                  * "auto_region_delete", which defaults to
3155                  * true (on). */
3156
3157                 LyXText * lt = bv_->getLyXText();
3158                 
3159                 if (lyxrc.auto_region_delete) {
3160                         if (lt->selection.set()) {
3161                                 lt->cutSelection(bv_, false, false);
3162                                 bv_->update(lt,
3163                                             BufferView::SELECT
3164                                             | BufferView::FITCUR
3165                                             | BufferView::CHANGE);
3166                         }
3167                 }
3168                 
3169                 beforeChange(lt);
3170                 LyXFont const old_font(lt->real_current_font);
3171                 
3172                 string::const_iterator cit = argument.begin();
3173                 string::const_iterator end = argument.end();
3174                 for (; cit != end; ++cit) {
3175                         owner_->getIntl()->getTrans().TranslateAndInsert(*cit, lt);
3176                 }
3177                 
3178                 bv_->update(lt,
3179                             BufferView::SELECT
3180                             | BufferView::FITCUR
3181                             | BufferView::CHANGE);
3182                 
3183                 lt->selection.cursor = lt->cursor;
3184                 moveCursorUpdate(false);
3185                 
3186                 // real_current_font.number can change so we need to
3187                 // update the minibuffer
3188                 if (old_font != lt->real_current_font)
3189                         owner_->showState();
3190                 //return string();
3191         }
3192         break;
3193
3194         case LFUN_DATE_INSERT:  // jdblair: date-insert cmd
3195         {
3196                 time_t now_time_t = time(NULL);
3197                 struct tm * now_tm = localtime(&now_time_t);
3198                 setlocale(LC_TIME, "");
3199                 string arg;
3200                 if (!argument.empty())
3201                         arg = argument;
3202                 else 
3203                         arg = lyxrc.date_insert_format;
3204                 char datetmp[32];
3205                 int const datetmp_len =
3206                         ::strftime(datetmp, 32, arg.c_str(), now_tm);
3207
3208                 LyXText * lt = bv_->getLyXText();
3209                 
3210                 for (int i = 0; i < datetmp_len; i++) {
3211                         lt->insertChar(bv_, datetmp[i]);
3212                         update(lt,
3213                                BufferView::SELECT
3214                                | BufferView::FITCUR
3215                                | BufferView::CHANGE);
3216                 }
3217
3218                 lt->selection.cursor = lt->cursor;
3219                 moveCursorUpdate(false);
3220         }
3221         break;
3222
3223         case LFUN_UNKNOWN_ACTION:
3224                 owner_->getLyXFunc()->setErrorMessage(N_("Unknown function!"));
3225                 break;
3226         
3227         default:
3228                 return false;
3229         } // end of switch
3230
3231         return true;
3232 }
3233
3234
3235 void BufferView::Pimpl::newline()
3236 {
3237         if (available()) {
3238                 LyXText * lt = bv_->getLyXText();
3239                 hideCursor();
3240                 update(lt,
3241                        BufferView::SELECT
3242                        | BufferView::FITCUR);
3243                 lt->insertChar(bv_, Paragraph::META_NEWLINE);
3244                 update(lt,
3245                        BufferView::SELECT
3246                        | BufferView::FITCUR
3247                        | BufferView::CHANGE);
3248         }
3249 }
3250
3251
3252 void BufferView::Pimpl::hfill()
3253 {
3254         if (available()) {
3255                 LyXText * lt = bv_->getLyXText();
3256                 hideCursor();
3257                 update(lt,
3258                        BufferView::SELECT
3259                        | BufferView::FITCUR);
3260                 lt->insertChar(bv_, Paragraph::META_HFILL);
3261                 update(lt,
3262                        BufferView::SELECT
3263                        | BufferView::FITCUR
3264                        | BufferView::CHANGE);
3265         }
3266 }
3267
3268
3269 void BufferView::Pimpl::protectedBlank(LyXText * lt)
3270 {
3271         if (available()) {
3272                 hideCursor();
3273                 update(lt, BufferView::SELECT|BufferView::FITCUR);
3274                 InsetSpecialChar * new_inset =
3275                         new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
3276 #ifdef WITH_WARNINGS
3277 #warning Why is this code different from specialChar() below? (JMarc)
3278 // the code in specialChar is a generic version of what used to exist
3279 // for other special chars. I did not merge this case because of the
3280 // call to updateInset(), but what does it do?
3281 #endif
3282                 if (!insertInset(new_inset))
3283                         delete new_inset;
3284                 else
3285                         updateInset(new_inset, true);
3286         }
3287 }
3288
3289
3290 void BufferView::Pimpl::specialChar(InsetSpecialChar::Kind kind)
3291 {
3292         if (available()) {
3293                 LyXText * lt = bv_->getLyXText();
3294                 
3295                 hideCursor();
3296                 update(lt, BufferView::SELECT|BufferView::FITCUR);
3297                 InsetSpecialChar * new_inset = 
3298                         new InsetSpecialChar(kind);
3299                 if (!insertInset(new_inset))
3300                         delete new_inset;
3301         }
3302 }
3303
3304
3305 void BufferView::Pimpl::smartQuote()
3306 {
3307         LyXText const * lt = bv_->getLyXText();
3308         Paragraph const * par = lt->cursor.par();
3309         pos_type pos = lt->cursor.pos();
3310         char c;
3311
3312         if (!pos
3313             || (par->isInset(pos - 1)
3314                 && par->getInset(pos - 1)->isSpace()))
3315                 c = ' ';
3316         else
3317                 c = par->getChar(pos - 1);
3318                 
3319
3320         hideCursor();
3321
3322         LyXLayout const & style = textclasslist.Style(
3323                 bv_->buffer()->params.textclass, par->getLayout());
3324         
3325         if (style.pass_thru ||
3326                 (!insertInset(new InsetQuotes(c, bv_->buffer()->params))))
3327                 bv_->owner()->getLyXFunc()->dispatch(LFUN_SELFINSERT, "\"");
3328 }
3329
3330
3331 void BufferView::Pimpl::insertAndEditInset(Inset * inset)
3332 {
3333         if (insertInset(inset))
3334                 inset->edit(bv_);
3335         else
3336                 delete inset;
3337 }
3338
3339  
3340 // Open and lock an updatable inset
3341 bool BufferView::Pimpl::open_new_inset(UpdatableInset * new_inset, bool behind)
3342 {
3343         LyXText * lt = bv_->getLyXText();
3344         
3345         beforeChange(lt);
3346         finishUndo();
3347         if (!insertInset(new_inset)) {
3348                 delete new_inset;
3349                 return false;
3350         }
3351         new_inset->edit(bv_, !behind);
3352         return true;
3353 }
3354
3355
3356 bool BufferView::Pimpl::insertInset(Inset * inset, string const & lout)
3357 {
3358         // if we are in a locking inset we should try to insert the
3359         // inset there otherwise this is a illegal function now
3360         if (bv_->theLockingInset()) {
3361                 if (bv_->theLockingInset()->insetAllowed(inset))
3362                     return bv_->theLockingInset()->insertInset(bv_, inset);
3363                 return false;
3364         }
3365
3366         // not quite sure if we want this...
3367         setCursorParUndo(bv_);
3368         freezeUndo();
3369         
3370         beforeChange(bv_->text);
3371         if (!lout.empty()) {
3372                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
3373                 bv_->text->breakParagraph(bv_);
3374                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
3375
3376                 if (bv_->text->cursor.par()->size()) {
3377                         bv_->text->cursorLeft(bv_);
3378                         
3379                         bv_->text->breakParagraph(bv_);
3380                         update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
3381                 }
3382
3383                 pair<bool, layout_type> lres =
3384                         textclasslist.NumberOfLayout(buffer_->params .textclass, lout);
3385                 layout_type lay = 0;
3386                 if (lres.first != false) {
3387                         // layout found
3388                         lay = lres.second;
3389                 } else {
3390                         // layout not fount using default "Standard" (0)
3391                         lay = 0;
3392                 }
3393                  
3394                 bv_->text->setLayout(bv_, lay);
3395                 
3396                 bv_->text->setParagraph(bv_, 0, 0,
3397                                    0, 0,
3398                                    VSpace(VSpace::NONE), VSpace(VSpace::NONE),
3399                                    Spacing(),
3400                                    LYX_ALIGN_LAYOUT, 
3401                                    string(),
3402                                    0);
3403                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
3404         }
3405         
3406         bv_->text->insertInset(bv_, inset);
3407         update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
3408
3409         unFreezeUndo();
3410         return true;
3411 }
3412
3413
3414 void BufferView::Pimpl::updateInset(Inset * inset, bool mark_dirty)
3415 {
3416         if (!inset)
3417                 return;
3418
3419         // first check for locking insets
3420         if (bv_->theLockingInset()) {
3421                 if (bv_->theLockingInset() == inset) {
3422                         if (bv_->text->updateInset(bv_, inset)) {
3423                                 update();
3424                                 if (mark_dirty) {
3425                                         buffer_->markDirty();
3426                                 }
3427                                 updateScrollbar();
3428                                 return;
3429                         }
3430                 } else if (bv_->theLockingInset()->updateInsetInInset(bv_, inset)) {
3431                         if (bv_->text->updateInset(bv_,  bv_->theLockingInset())) {
3432                                 update();
3433                                 if (mark_dirty) {
3434                                         buffer_->markDirty();
3435                                 }
3436                                 updateScrollbar();
3437                                 return;
3438                         }
3439                 }
3440         }
3441   
3442         // then check the current buffer
3443         if (available()) {
3444                 hideCursor();
3445                 update(bv_->text, BufferView::UPDATE);
3446                 if (bv_->text->updateInset(bv_, inset)) {
3447                         if (mark_dirty) {
3448                                 update(bv_->text,
3449                                        BufferView::SELECT
3450                                        | BufferView::FITCUR
3451                                        | BufferView::CHANGE);
3452                         } else {
3453                                 update(bv_->text, SELECT);
3454                         }
3455                         return;
3456                 }
3457         }
3458 }
3459
3460
3461 void BufferView::Pimpl::gotoInset(vector<Inset::Code> const & codes,
3462                                   bool same_content)
3463 {
3464         if (!available()) return;
3465         
3466         hideCursor();
3467         beforeChange(bv_->text);
3468         update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
3469         
3470         LyXCursor const & cursor = bv_->text->cursor;
3471  
3472         string contents;
3473         if (same_content &&
3474             cursor.par()->isInset(cursor.pos())) {
3475                 Inset const * inset = cursor.par()->getInset(cursor.pos());
3476                 if (find(codes.begin(), codes.end(), inset->lyxCode())
3477                     != codes.end())
3478                         contents =
3479                                 static_cast<InsetCommand const *>(inset)->getContents();
3480         }
3481         
3482  
3483         if (!bv_->text->gotoNextInset(bv_, codes, contents)) {
3484                 if (bv_->text->cursor.pos() 
3485                     || bv_->text->cursor.par() != bv_->text->ownerParagraph()) {
3486                         LyXCursor tmp = bv_->text->cursor;
3487                         bv_->text->cursor.par(bv_->text->ownerParagraph());
3488                         bv_->text->cursor.pos(0);
3489                         if (!bv_->text->gotoNextInset(bv_, codes, contents)) {
3490                                 bv_->text->cursor = tmp;
3491                                 bv_->owner()->message(_("No more insets"));
3492                         }
3493                 } else {
3494                         bv_->owner()->message(_("No more insets"));
3495                 }
3496         }
3497         update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
3498         bv_->text->selection.cursor = bv_->text->cursor;
3499 }
3500
3501
3502 void BufferView::Pimpl::gotoInset(Inset::Code code, bool same_content)
3503 {
3504         gotoInset(vector<Inset::Code>(1, code), same_content);
3505 }