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