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