]> git.lyx.org Git - lyx.git/blob - src/BufferView.cpp
* lib/ui/stdmenues.inc: rename "Table Of Contents" to "Outline"
[lyx.git] / src / BufferView.cpp
1 /**
2  * \file BufferView.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alfredo Braunstein
7  * \author Lars Gullik Bjønnes
8  * \author John Levon
9  * \author André Pönitz
10  * \author Jürgen Vigna
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "BufferView.h"
18
19 #include "Buffer.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "bufferview_funcs.h"
24 #include "CoordCache.h"
25 #include "CutAndPaste.h"
26 #include "debug.h"
27 #include "DispatchResult.h"
28 #include "ErrorList.h"
29 #include "factory.h"
30 #include "FloatList.h"
31 #include "FuncRequest.h"
32 #include "FuncStatus.h"
33 #include "gettext.h"
34 #include "Intl.h"
35 #include "InsetIterator.h"
36 #include "Language.h"
37 #include "LaTeXFeatures.h"
38 #include "callback.h" // added for Dispatch functions
39 #include "LyX.h"
40 #include "lyxfind.h"
41 #include "LyXFunc.h"
42 #include "Layout.h"
43 #include "Text.h"
44 #include "TextClass.h"
45 #include "LyXRC.h"
46 #include "Session.h"
47 #include "Paragraph.h"
48 #include "paragraph_funcs.h"
49 #include "ParagraphParameters.h"
50 #include "ParIterator.h"
51 #include "TexRow.h"
52 #include "toc.h"
53 #include "Undo.h"
54 #include "VSpace.h"
55 #include "WordLangTuple.h"
56 #include "MetricsInfo.h"
57
58 #include "insets/InsetBibtex.h"
59 #include "insets/InsetCommand.h" // ChangeRefs
60 #include "insets/InsetRef.h"
61 #include "insets/InsetText.h"
62
63 #include "frontends/alert.h"
64 #include "frontends/FileDialog.h"
65 #include "frontends/FontMetrics.h"
66
67 #include "graphics/Previews.h"
68
69 #include "support/convert.h"
70 #include "support/FileFilterList.h"
71 #include "support/filetools.h"
72 #include "support/Package.h"
73 #include "support/types.h"
74
75 #include <boost/bind.hpp>
76 #include <boost/current_function.hpp>
77
78 #include <functional>
79 #include <vector>
80
81
82 namespace lyx {
83
84 using support::addPath;
85 using support::bformat;
86 using support::FileFilterList;
87 using support::FileName;
88 using support::fileSearch;
89 using support::isDirWriteable;
90 using support::isFileReadable;
91 using support::makeDisplayPath;
92 using support::package;
93
94 using std::distance;
95 using std::endl;
96 using std::istringstream;
97 using std::make_pair;
98 using std::min;
99 using std::max;
100 using std::mem_fun_ref;
101 using std::string;
102 using std::vector;
103
104 namespace Alert = frontend::Alert;
105
106 namespace {
107
108 /// Return an inset of this class if it exists at the current cursor position
109 template <class T>
110 T * getInsetByCode(Cursor & cur, Inset::Code code)
111 {
112         T * inset = 0;
113         DocIterator it = cur;
114         if (it.nextInset() &&
115             it.nextInset()->lyxCode() == code) {
116                 inset = static_cast<T*>(it.nextInset());
117         }
118         return inset;
119 }
120
121 } // anon namespace
122
123
124 BufferView::BufferView()
125         : width_(0), height_(0), buffer_(0), wh_(0),
126           cursor_(*this),
127           multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
128           intl_(new Intl), last_inset_(0)
129 {
130         xsel_cache_.set = false;
131         intl_->initKeyMapper(lyxrc.use_kbmap);
132 }
133
134
135 BufferView::~BufferView()
136 {
137 }
138
139
140 Buffer * BufferView::buffer() const
141 {
142         return buffer_;
143 }
144
145
146 void BufferView::setBuffer(Buffer * b)
147 {
148         LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
149                             << "[ b = " << b << "]" << endl;
150
151         if (buffer_) {
152                 // Save the actual cursor position and anchor inside the
153                 // buffer so that it can be restored in case we rechange
154                 // to this buffer later on.
155                 buffer_->saveCursor(cursor_.selectionBegin(),
156                                     cursor_.selectionEnd());
157                 // update bookmark pit of the current buffer before switch
158                 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i) {
159                         BookmarksSection::Bookmark const & bm = LyX::ref().session().bookmarks().bookmark(i);
160                         if (buffer()->fileName() != bm.filename.absFilename())
161                                 continue;
162                         // if top_id or bottom_pit, bottom_pos has been changed, update bookmark
163                         // see http://bugzilla.lyx.org/show_bug.cgi?id=3092
164                         pit_type new_pit;
165                         pos_type new_pos;
166                         int new_id;
167                         boost::tie(new_pit, new_pos, new_id) = moveToPosition(bm.bottom_pit, bm.bottom_pos, bm.top_id, bm.top_pos);
168                         if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos || bm.top_id != new_id )
169                                 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(new_pit, new_pos, new_id);
170                 }
171                 // current buffer is going to be switched-off, save cursor pos
172                 // Ideally, the whole cursor stack should be saved, but session
173                 // currently can only handle bottom (whole document) level pit and pos.
174                 // That is to say, if a cursor is in a nested inset, it will be
175                 // restore to the left of the top level inset.
176                 LyX::ref().session().lastFilePos().save(FileName(buffer_->fileName()),
177                         boost::tie(cursor_.bottom().pit(), cursor_.bottom().pos()) );
178         }
179
180         // If we're quitting lyx, don't bother updating stuff
181         if (quitting) {
182                 buffer_ = 0;
183                 return;
184         }
185
186         // If we are closing current buffer, switch to the first in
187         // buffer list.
188         if (!b) {
189                 LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
190                                     << " No Buffer!" << endl;
191                 // We are closing the buffer, use the first buffer as current
192                 buffer_ = theBufferList().first();
193         } else {
194                 // Set current buffer
195                 buffer_ = b;
196         }
197
198         // Reset old cursor
199         cursor_ = Cursor(*this);
200         anchor_ref_ = 0;
201         offset_ref_ = 0;
202
203         if (buffer_) {
204                 LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
205                                     << "Buffer addr: " << buffer_ << endl;
206                 cursor_.push(buffer_->inset());
207                 cursor_.resetAnchor();
208                 buffer_->text().setCurrentFont(cursor_);
209                 if (buffer_->getCursor().size() > 0 &&
210                     buffer_->getAnchor().size() > 0)
211                 {
212                         cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
213                         cursor_.resetAnchor();
214                         cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
215                         cursor_.setSelection();
216                         // do not set selection to the new buffer because we
217                         // only paste recent selection.
218
219                         // Make sure that the restored cursor is not broken. This can happen for
220                         // example if this Buffer has been modified by another view.
221                         cursor_.fixIfBroken();
222                 }
223         }
224
225         if (buffer_)
226                 updateMetrics(false);    
227
228         if (buffer_ && graphics::Previews::status() != LyXRC::PREVIEW_OFF)
229                 graphics::Previews::get().generateBufferPreviews(*buffer_);
230 }
231
232
233 bool BufferView::loadLyXFile(FileName const & filename, bool tolastfiles)
234 {
235         // File already open?
236         if (theBufferList().exists(filename.absFilename())) {
237                 docstring const file = makeDisplayPath(filename.absFilename(), 20);
238                 docstring text = bformat(_("The document %1$s is already "
239                                                      "loaded.\n\nDo you want to revert "
240                                                      "to the saved version?"), file);
241                 int const ret = Alert::prompt(_("Revert to saved document?"),
242                         text, 0, 1,  _("&Revert"), _("&Switch to document"));
243
244                 if (ret != 0) {
245                         setBuffer(theBufferList().getBuffer(filename.absFilename()));
246                         return true;
247                 }
248                 // FIXME: should be LFUN_REVERT
249                 if (!theBufferList().close(theBufferList().getBuffer(filename.absFilename()), false))
250                         return false;
251                 // Fall through to new load. (Asger)
252                 buffer_ = 0;
253         }
254
255         Buffer * b = 0;
256
257         if (isFileReadable(filename)) {
258                 b = theBufferList().newBuffer(filename.absFilename());
259                 if (!lyx::loadLyXFile(b, filename)) {
260                         theBufferList().release(b);
261                         return false;
262                 }
263         } else {
264                 docstring text = bformat(_("The document %1$s does not yet "
265                                                      "exist.\n\nDo you want to create "
266                                                      "a new document?"), from_utf8(filename.absFilename()));
267                 int const ret = Alert::prompt(_("Create new document?"),
268                          text, 0, 1, _("&Create"), _("Cancel"));
269
270                 if (ret == 0) {
271                         b = newFile(filename.absFilename(), string(), true);
272                         if (!b)
273                                 return false;
274                 } else
275                         return false;
276         }
277
278         setBuffer(b);
279         // Send the "errors" signal in case of parsing errors
280         b->errors("Parse");
281
282         // Update the labels and section numbering.
283         updateLabels(*buffer_);
284         // scroll to the position when the file was last closed
285         if (lyxrc.use_lastfilepos) {
286                 pit_type pit;
287                 pos_type pos;
288                 boost::tie(pit, pos) = LyX::ref().session().lastFilePos().load(filename);
289                 // if successfully move to pit (returned par_id is not zero), update metrics and reset font
290                 if (moveToPosition(pit, pos, 0, 0).get<1>()) {
291                         if (fitCursor())
292                                 updateMetrics(false);
293                         buffer_->text().setCurrentFont(cursor_);
294                 }
295         }
296
297         if (tolastfiles)
298                 LyX::ref().session().lastFiles().add(FileName(b->fileName()));
299
300         return true;
301 }
302
303
304 void BufferView::resize()
305 {
306         if (!buffer_)
307                 return;
308
309         LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION << endl;
310
311         updateMetrics(false);
312         switchKeyMap();
313 }
314
315
316 bool BufferView::fitCursor()
317 {
318         if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
319                 frontend::FontMetrics const & fm =
320                         theFontMetrics(cursor_.getFont());
321                 int const asc = fm.maxAscent();
322                 int const des = fm.maxDescent();
323                 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
324                 if (p.y_ - asc >= 0 && p.y_ + des < height_)
325                         return false;
326         }
327         center();
328         return true;
329 }
330
331
332 bool BufferView::multiParSel()
333 {
334         if (!cursor_.selection())
335                 return false;
336         bool ret = multiparsel_cache_;
337         multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
338         // Either this, or previous selection spans paragraphs
339         return ret || multiparsel_cache_;
340 }
341
342
343 bool BufferView::update(Update::flags flags)
344 {
345         // last_inset_ points to the last visited inset. This pointer may become
346         // invalid because of keyboard editing. Since all such operations
347         // causes screen update(), I reset last_inset_ to avoid such a problem.
348         last_inset_ = 0;
349         // This is close to a hot-path.
350         LYXERR(Debug::DEBUG)
351                 << BOOST_CURRENT_FUNCTION
352                 << "[fitcursor = " << (flags & Update::FitCursor)
353                 << ", forceupdate = " << (flags & Update::Force)
354                 << ", singlepar = " << (flags & Update::SinglePar)
355                 << "]  buffer: " << buffer_ << endl;
356
357         // Check needed to survive LyX startup
358         if (!buffer_)
359                 return false;
360
361         LYXERR(Debug::WORKAREA) << "BufferView::update" << std::endl;
362
363         // Update macro store
364         if (!(cursor().inMathed() && cursor().inMacroMode()))
365                 buffer_->buildMacros();
366
367         // Now do the first drawing step if needed. This consists on updating
368         // the CoordCache in updateMetrics().
369         // The second drawing step is done in WorkArea::redraw() if needed.
370
371         // Case when no explicit update is requested.
372         if (!flags) {
373                 // no need to redraw anything.
374                 metrics_info_.update_strategy = NoScreenUpdate;
375                 return false;
376         }
377
378         if (flags == Update::Decoration) {
379                 metrics_info_.update_strategy = DecorationUpdate;
380                 return true;
381         }
382
383         if (flags == Update::FitCursor 
384                 || flags == (Update::Decoration | Update::FitCursor)) {
385                 bool const fit_cursor = fitCursor();
386                 // tell the frontend to update the screen if needed.
387                 if (fit_cursor) {
388                         updateMetrics(false);
389                         return true;
390                 }
391                 if (flags & Update::Decoration) {
392                         metrics_info_.update_strategy = DecorationUpdate;
393                         return true;
394                 }
395                 // no screen update is needed.
396                 metrics_info_.update_strategy = NoScreenUpdate;
397                 return false;
398         }
399
400         bool full_metrics = flags & Update::Force;
401         if (flags & Update::MultiParSel)
402                 full_metrics |= multiParSel();
403
404         bool const single_par = !full_metrics;
405         updateMetrics(single_par);
406
407         if (flags & Update::FitCursor && fitCursor())
408                 updateMetrics(false);
409
410         // tell the frontend to update the screen.
411         return true;
412 }
413
414
415 void BufferView::updateScrollbar()
416 {
417         if (!buffer_) {
418                 LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION
419                                      << " no text in updateScrollbar" << endl;
420                 scrollbarParameters_.reset();
421                 return;
422         }
423
424         Text & t = buffer_->text();
425         TextMetrics & tm = text_metrics_[&t];
426
427         int const parsize = int(t.paragraphs().size() - 1);
428         if (anchor_ref_ >  parsize)  {
429                 anchor_ref_ = parsize;
430                 offset_ref_ = 0;
431         }
432
433         LYXERR(Debug::GUI)
434                 << BOOST_CURRENT_FUNCTION
435                 << " Updating scrollbar: height: " << t.paragraphs().size()
436                 << " curr par: " << cursor_.bottom().pit()
437                 << " default height " << defaultRowHeight() << endl;
438
439         // It would be better to fix the scrollbar to understand
440         // values in [0..1] and divide everything by wh
441
442         // estimated average paragraph height:
443         if (wh_ == 0)
444                 wh_ = height_ / 4;
445
446         int h = tm.parMetrics(anchor_ref_).height();
447
448         // Normalize anchor/offset (MV):
449         while (offset_ref_ > h && anchor_ref_ < parsize) {
450                 anchor_ref_++;
451                 offset_ref_ -= h;
452                 h = tm.parMetrics(anchor_ref_).height();
453         }
454         // Look at paragraph heights on-screen
455         int sumh = 0;
456         int nh = 0;
457         for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
458                 if (sumh > height_)
459                         break;
460                 int const h2 = tm.parMetrics(pit).height();
461                 sumh += h2;
462                 nh++;
463         }
464
465         BOOST_ASSERT(nh);
466         int const hav = sumh / nh;
467         // More realistic average paragraph height
468         if (hav > wh_)
469                 wh_ = hav;
470
471         BOOST_ASSERT(h);
472         scrollbarParameters_.height = (parsize + 1) * wh_;
473         scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
474         scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
475 }
476
477
478 ScrollbarParameters const & BufferView::scrollbarParameters() const
479 {
480         return scrollbarParameters_;
481 }
482
483
484 void BufferView::scrollDocView(int value)
485 {
486         LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
487                            << "[ value = " << value << "]" << endl;
488
489         if (!buffer_)
490                 return;
491
492         Text & t = buffer_->text();
493         TextMetrics & tm = text_metrics_[&t];
494
495         float const bar = value / float(wh_ * t.paragraphs().size());
496
497         anchor_ref_ = int(bar * t.paragraphs().size());
498         if (anchor_ref_ >  int(t.paragraphs().size()) - 1)
499                 anchor_ref_ = int(t.paragraphs().size()) - 1;
500
501         tm.redoParagraph(anchor_ref_);
502         int const h = tm.parMetrics(anchor_ref_).height();
503         offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
504         updateMetrics(false);
505 }
506
507
508 void BufferView::setCursorFromScrollbar()
509 {
510         if (!buffer_)
511                 return;
512
513         Text & t = buffer_->text();
514
515         int const height = 2 * defaultRowHeight();
516         int const first = height;
517         int const last = height_ - height;
518         Cursor & cur = cursor_;
519
520         bv_funcs::CurStatus st = bv_funcs::status(this, cur);
521
522         switch (st) {
523         case bv_funcs::CUR_ABOVE:
524                 // We reset the cursor because bv_funcs::status() does not
525                 // work when the cursor is within mathed.
526                 cur.reset(buffer_->inset());
527                 t.setCursorFromCoordinates(cur, 0, first);
528                 cur.clearSelection();
529                 break;
530         case bv_funcs::CUR_BELOW:
531                 // We reset the cursor because bv_funcs::status() does not
532                 // work when the cursor is within mathed.
533                 cur.reset(buffer_->inset());
534                 t.setCursorFromCoordinates(cur, 0, last);
535                 cur.clearSelection();
536                 break;
537         case bv_funcs::CUR_INSIDE:
538                 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
539                 int const newy = min(last, max(y, first));
540                 if (y != newy) {
541                         cur.reset(buffer_->inset());
542                         t.setCursorFromCoordinates(cur, 0, newy);
543                 }
544         }
545 }
546
547
548 Change const BufferView::getCurrentChange() const
549 {
550         if (!cursor_.selection())
551                 return Change(Change::UNCHANGED);
552
553         DocIterator dit = cursor_.selectionBegin();
554         return dit.paragraph().lookupChange(dit.pos());
555 }
556
557
558 void BufferView::saveBookmark(unsigned int idx)
559 {
560         // tenatively save bookmark, id and pos will be used to
561         // acturately locate a bookmark in a 'live' lyx session.
562         // pit and pos will be updated with bottom level pit/pos 
563         // when lyx exits.
564         LyX::ref().session().bookmarks().save(
565                 FileName(buffer_->fileName()),
566                 cursor_.bottom().pit(),
567                 cursor_.bottom().pos(),
568                 cursor_.paragraph().id(),
569                 cursor_.pos(),
570                 idx
571         );
572         if (idx)
573                 // emit message signal.
574                 message(_("Save bookmark"));
575 }
576
577
578 boost::tuple<pit_type, pos_type, int> BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
579         int top_id, pos_type top_pos)
580 {
581         cursor_.clearSelection();
582
583         // if a valid par_id is given, try it first
584         // This is the case for a 'live' bookmark when unique paragraph ID
585         // is used to track bookmarks.
586         if (top_id > 0) {
587                 ParIterator par = buffer_->getParFromID(top_id);
588                 if (par != buffer_->par_iterator_end()) {
589                         DocIterator dit = makeDocIterator(par, min(par->size(), top_pos));
590                         // Some slices of the iterator may not be
591                         // reachable (e.g. closed collapsable inset)
592                         // so the dociterator may need to be
593                         // shortened. Otherwise, setCursor may crash
594                         // lyx when the cursor can not be set to these
595                         // insets.
596                         size_t const n = dit.depth();
597                         for (size_t i = 0; i < n; ++i)
598                                 if (dit[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
599                                         dit.resize(i);
600                                         break;
601                                 }
602                         setCursor(dit);
603                         // Note: return bottom (document) level pit.
604                         return boost::make_tuple(cursor_.bottom().pit(), cursor_.bottom().pos(), top_id);
605                 }
606         }
607         // if top_id == 0, or searching through top_id failed
608         // This is the case for a 'restored' bookmark when only bottom 
609         // (document level) pit was saved. Because of this, bookmark
610         // restoration is inaccurate. If a bookmark was within an inset,
611         // it will be restored to the left of the outmost inset that contains
612         // the bookmark.
613         if (static_cast<size_t>(bottom_pit) < buffer_->paragraphs().size()) {
614                 DocIterator it = doc_iterator_begin(buffer_->inset());
615                 it.pit() = bottom_pit;
616                 it.pos() = min(bottom_pos, it.paragraph().size());
617                 setCursor(it);
618                 return boost::make_tuple(it.pit(), it.pos(), 
619                                          it.paragraph().id());
620         }
621         // both methods fail
622         return boost::make_tuple(pit_type(0), pos_type(0), 0);
623 }
624
625
626 void BufferView::switchKeyMap()
627 {
628         if (!lyxrc.rtl_support)
629                 return;
630
631         if (cursor_.innerText()->real_current_font.isRightToLeft()) {
632                 if (intl_->keymap == Intl::PRIMARY)
633                         intl_->keyMapSec();
634         } else {
635                 if (intl_->keymap == Intl::SECONDARY)
636                         intl_->keyMapPrim();
637         }
638 }
639
640
641 int BufferView::workWidth() const
642 {
643         return width_;
644 }
645
646
647 void BufferView::center()
648 {
649         CursorSlice & bot = cursor_.bottom();
650         TextMetrics & tm = text_metrics_[bot.text()];
651         pit_type const pit = bot.pit();
652         tm.redoParagraph(pit);
653         ParagraphMetrics const & pm = tm.parMetrics(pit);
654         anchor_ref_ = pit;
655         offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
656                 + pm.ascent() - height_ / 2;
657 }
658
659
660 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
661 {
662         FuncStatus flag;
663
664         switch (cmd.action) {
665
666         case LFUN_UNDO:
667                 flag.enabled(!buffer_->undostack().empty());
668                 break;
669         case LFUN_REDO:
670                 flag.enabled(!buffer_->redostack().empty());
671                 break;
672         case LFUN_FILE_INSERT:
673         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
674         case LFUN_FILE_INSERT_PLAINTEXT:
675         case LFUN_BOOKMARK_SAVE:
676                 // FIXME: Actually, these LFUNS should be moved to Text
677                 flag.enabled(cursor_.inTexted());
678                 break;
679         case LFUN_FONT_STATE:
680         case LFUN_LABEL_INSERT:
681         case LFUN_PARAGRAPH_GOTO:
682         // FIXME handle non-trivially
683         case LFUN_OUTLINE_UP:
684         case LFUN_OUTLINE_DOWN:
685         case LFUN_OUTLINE_IN:
686         case LFUN_OUTLINE_OUT:
687         case LFUN_NOTE_NEXT:
688         case LFUN_REFERENCE_NEXT:
689         case LFUN_WORD_FIND:
690         case LFUN_WORD_REPLACE:
691         case LFUN_MARK_OFF:
692         case LFUN_MARK_ON:
693         case LFUN_MARK_TOGGLE:
694         case LFUN_SCREEN_RECENTER:
695         case LFUN_BIBTEX_DATABASE_ADD:
696         case LFUN_BIBTEX_DATABASE_DEL:
697         case LFUN_WORDS_COUNT:
698         case LFUN_NEXT_INSET_TOGGLE:
699                 flag.enabled(true);
700                 break;
701
702         case LFUN_LABEL_GOTO: {
703                 flag.enabled(!cmd.argument().empty()
704                     || getInsetByCode<InsetRef>(cursor_, Inset::REF_CODE));
705                 break;
706         }
707
708         case LFUN_CHANGES_TRACK:
709                 flag.enabled(true);
710                 flag.setOnOff(buffer_->params().trackChanges);
711                 break;
712
713         case LFUN_CHANGES_OUTPUT:
714                 flag.enabled(buffer_);
715                 flag.setOnOff(buffer_->params().outputChanges);
716                 break;
717
718         case LFUN_CHANGES_MERGE:
719         case LFUN_CHANGE_NEXT:
720         case LFUN_ALL_CHANGES_ACCEPT:
721         case LFUN_ALL_CHANGES_REJECT:
722                 // TODO: context-sensitive enabling of LFUNs
723                 // In principle, these command should only be enabled if there
724                 // is a change in the document. However, without proper
725                 // optimizations, this will inevitably result in poor performance.
726                 flag.enabled(buffer_);
727                 break;
728
729         case LFUN_BUFFER_TOGGLE_COMPRESSION: {
730                 flag.setOnOff(buffer_->params().compressed);
731                 break;
732         }
733
734         default:
735                 flag.enabled(false);
736         }
737
738         return flag;
739 }
740
741
742 Update::flags BufferView::dispatch(FuncRequest const & cmd)
743 {
744         //lyxerr << BOOST_CURRENT_FUNCTION
745         //       << [ cmd = " << cmd << "]" << endl;
746
747         // Make sure that the cached BufferView is correct.
748         LYXERR(Debug::ACTION) << BOOST_CURRENT_FUNCTION
749                 << " action[" << cmd.action << ']'
750                 << " arg[" << to_utf8(cmd.argument()) << ']'
751                 << " x[" << cmd.x << ']'
752                 << " y[" << cmd.y << ']'
753                 << " button[" << cmd.button() << ']'
754                 << endl;
755
756         // FIXME: this should not be possible.
757         if (!buffer_)
758                 return Update::None;
759
760         Cursor & cur = cursor_;
761         // Default Update flags.
762         Update::flags updateFlags = Update::Force | Update::FitCursor;
763
764         switch (cmd.action) {
765
766         case LFUN_UNDO:
767                 cur.message(_("Undo"));
768                 cur.clearSelection();
769                 if (!textUndo(*this)) {
770                         cur.message(_("No further undo information"));
771                         updateFlags = Update::None;
772                 }
773                 switchKeyMap();
774                 break;
775
776         case LFUN_REDO:
777                 cur.message(_("Redo"));
778                 cur.clearSelection();
779                 if (!textRedo(*this)) {
780                         cur.message(_("No further redo information"));
781                         updateFlags = Update::None;
782                 }
783                 switchKeyMap();
784                 break;
785
786         case LFUN_FILE_INSERT:
787                 // FIXME UNICODE
788                 menuInsertLyXFile(to_utf8(cmd.argument()));
789                 break;
790
791         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
792                 // FIXME UNICODE
793                 insertPlaintextFile(this, to_utf8(cmd.argument()), true);
794                 break;
795
796         case LFUN_FILE_INSERT_PLAINTEXT:
797                 // FIXME UNICODE
798                 insertPlaintextFile(this, to_utf8(cmd.argument()), false);
799                 break;
800
801         case LFUN_FONT_STATE:
802                 cur.message(cur.currentState());
803                 break;
804
805         case LFUN_BOOKMARK_SAVE:
806                 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
807                 break;
808
809         case LFUN_LABEL_GOTO: {
810                 docstring label = cmd.argument();
811                 if (label.empty()) {
812                         InsetRef * inset =
813                                 getInsetByCode<InsetRef>(cursor_,
814                                                          Inset::REF_CODE);
815                         if (inset) {
816                                 label = inset->getParam("reference");
817                                 // persistent=false: use temp_bookmark
818                                 saveBookmark(0);
819                         }
820                 }
821
822                 if (!label.empty())
823                         gotoLabel(label);
824                 break;
825         }
826
827         case LFUN_PARAGRAPH_GOTO: {
828                 int const id = convert<int>(to_utf8(cmd.argument()));
829                 int i = 0;
830                 for (Buffer * b = buffer_; i == 0 || b != buffer_; b = theBufferList().next(b)) {
831                         ParIterator par = b->getParFromID(id);
832                         if (par == b->par_iterator_end()) {
833                                 LYXERR(Debug::INFO)
834                                         << "No matching paragraph found! ["
835                                         << id << "]." << endl;
836                         } else {
837                                 LYXERR(Debug::INFO)
838                                         << "Paragraph " << par->id()
839                                         << " found in buffer `"
840                                         << b->fileName() << "'." << endl;
841
842                                 if (b == buffer_) {
843                                         // Set the cursor
844                                         setCursor(makeDocIterator(par, 0));
845                                         switchKeyMap();
846                                 } else {
847                                         // Switch to other buffer view and resend cmd
848                                         theLyXFunc().dispatch(FuncRequest(
849                                                 LFUN_BUFFER_SWITCH, b->fileName()));
850                                         theLyXFunc().dispatch(cmd);
851                                         updateFlags = Update::None;
852                                 }
853                                 break;
854                         }
855                         ++i;
856                 }
857                 break;
858         }
859
860         case LFUN_OUTLINE_UP:
861                 toc::outline(toc::Up, cursor_);
862                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
863                 updateLabels(*buffer_);
864                 break;
865         case LFUN_OUTLINE_DOWN:
866                 toc::outline(toc::Down, cursor_);
867                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
868                 updateLabels(*buffer_);
869                 break;
870         case LFUN_OUTLINE_IN:
871                 toc::outline(toc::In, cursor_);
872                 updateLabels(*buffer_);
873                 break;
874         case LFUN_OUTLINE_OUT:
875                 toc::outline(toc::Out, cursor_);
876                 updateLabels(*buffer_);
877                 break;
878
879         case LFUN_NOTE_NEXT:
880                 bv_funcs::gotoInset(this, Inset::NOTE_CODE, false);
881                 break;
882
883         case LFUN_REFERENCE_NEXT: {
884                 vector<Inset_code> tmp;
885                 tmp.push_back(Inset::LABEL_CODE);
886                 tmp.push_back(Inset::REF_CODE);
887                 bv_funcs::gotoInset(this, tmp, true);
888                 break;
889         }
890
891         case LFUN_CHANGES_TRACK:
892                 buffer_->params().trackChanges = !buffer_->params().trackChanges;
893                 break;
894
895         case LFUN_CHANGES_OUTPUT:
896                 buffer_->params().outputChanges = !buffer_->params().outputChanges;
897                 if (buffer_->params().outputChanges) {
898                         bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
899                         bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
900                                           LaTeXFeatures::isAvailable("xcolor");
901                 
902                         if (!dvipost && !xcolorsoul) {
903                                 Alert::warning(_("Changes not shown in LaTeX output"),
904                                                _("Changes will not be highlighted in LaTeX output, "
905                                                  "because neither dvipost nor xcolor/soul are installed.\n"
906                                                  "Please install these packages or redefine "
907                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
908                         } else if (!xcolorsoul) {
909                                 Alert::warning(_("Changes not shown in LaTeX output"),
910                                                _("Changes will not be highlighted in LaTeX output "
911                                                  "when using pdflatex, because xcolor and soul are not installed.\n"
912                                                  "Please install both packages or redefine "
913                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
914                         }
915                 }
916                 break;
917
918         case LFUN_CHANGE_NEXT:
919                 findNextChange(this);
920                 break;
921
922         case LFUN_CHANGES_MERGE:
923                 if (findNextChange(this))
924                         showDialog("changes");
925                 break;
926
927         case LFUN_ALL_CHANGES_ACCEPT:
928                 // select complete document
929                 cursor_.reset(buffer_->inset());
930                 cursor_.selHandle(true);
931                 buffer_->text().cursorBottom(cursor_);
932                 // accept everything in a single step to support atomic undo
933                 buffer_->text().acceptOrRejectChanges(cursor_, Text::ACCEPT);
934                 break;
935
936         case LFUN_ALL_CHANGES_REJECT:
937                 // select complete document
938                 cursor_.reset(buffer_->inset());
939                 cursor_.selHandle(true);
940                 buffer_->text().cursorBottom(cursor_);
941                 // reject everything in a single step to support atomic undo
942                 // Note: reject does not work recursively; the user may have to repeat the operation
943                 buffer_->text().acceptOrRejectChanges(cursor_, Text::REJECT);
944                 break;
945
946         case LFUN_WORD_FIND:
947                 find(this, cmd);
948                 break;
949
950         case LFUN_WORD_REPLACE:
951                 replace(this, cmd);
952                 break;
953
954         case LFUN_MARK_OFF:
955                 cur.clearSelection();
956                 cur.resetAnchor();
957                 cur.message(from_utf8(N_("Mark off")));
958                 break;
959
960         case LFUN_MARK_ON:
961                 cur.clearSelection();
962                 cur.mark() = true;
963                 cur.resetAnchor();
964                 cur.message(from_utf8(N_("Mark on")));
965                 break;
966
967         case LFUN_MARK_TOGGLE:
968                 cur.clearSelection();
969                 if (cur.mark()) {
970                         cur.mark() = false;
971                         cur.message(from_utf8(N_("Mark removed")));
972                 } else {
973                         cur.mark() = true;
974                         cur.message(from_utf8(N_("Mark set")));
975                 }
976                 cur.resetAnchor();
977                 break;
978
979         case LFUN_SCREEN_RECENTER:
980                 center();
981                 break;
982
983         case LFUN_BIBTEX_DATABASE_ADD: {
984                 Cursor tmpcur = cursor_;
985                 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
986                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
987                                                 Inset::BIBTEX_CODE);
988                 if (inset) {
989                         if (inset->addDatabase(to_utf8(cmd.argument())))
990                                 buffer_->updateBibfilesCache();
991                 }
992                 break;
993         }
994
995         case LFUN_BIBTEX_DATABASE_DEL: {
996                 Cursor tmpcur = cursor_;
997                 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
998                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
999                                                 Inset::BIBTEX_CODE);
1000                 if (inset) {
1001                         if (inset->delDatabase(to_utf8(cmd.argument())))
1002                                 buffer_->updateBibfilesCache();
1003                 }
1004                 break;
1005         }
1006
1007         case LFUN_WORDS_COUNT: {
1008                 DocIterator from, to;
1009                 if (cur.selection()) {
1010                         from = cur.selectionBegin();
1011                         to = cur.selectionEnd();
1012                 } else {
1013                         from = doc_iterator_begin(buffer_->inset());
1014                         to = doc_iterator_end(buffer_->inset());
1015                 }
1016                 int const count = countWords(from, to);
1017                 docstring message;
1018                 if (count != 1) {
1019                         if (cur.selection())
1020                                 message = bformat(_("%1$d words in selection."),
1021                                           count);
1022                                 else
1023                                         message = bformat(_("%1$d words in document."),
1024                                                           count);
1025                 }
1026                 else {
1027                         if (cur.selection())
1028                                 message = _("One word in selection.");
1029                         else
1030                                 message = _("One word in document.");
1031                 }
1032
1033                 Alert::information(_("Count words"), message);
1034         }
1035                 break;
1036
1037         case LFUN_BUFFER_TOGGLE_COMPRESSION:
1038                 // turn compression on/off
1039                 buffer_->params().compressed = !buffer_->params().compressed;
1040                 break;
1041
1042         case LFUN_NEXT_INSET_TOGGLE: {
1043                 // this is the real function we want to invoke
1044                 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1045                 // if there is an inset at cursor, see whether it
1046                 // wants to toggle.
1047                 Inset * inset = cur.nextInset();
1048                 if (inset && inset->isActive()) {
1049                         Cursor tmpcur = cur;
1050                         tmpcur.pushLeft(*inset);
1051                         inset->dispatch(tmpcur, tmpcmd);
1052                         if (tmpcur.result().dispatched()) {
1053                                 cur.dispatched();
1054                         }
1055                 }
1056                 // if it did not work, try the underlying inset.
1057                 if (!cur.result().dispatched())
1058                         cur.dispatch(tmpcmd);
1059
1060                 if (cur.result().dispatched())
1061                         cur.clearSelection();
1062
1063                 break;
1064         }
1065
1066         default:
1067                 updateFlags = Update::None;
1068         }
1069
1070         return updateFlags;
1071 }
1072
1073
1074 docstring const BufferView::requestSelection()
1075 {
1076         if (!buffer_)
1077                 return docstring();
1078
1079         Cursor & cur = cursor_;
1080
1081         if (!cur.selection()) {
1082                 xsel_cache_.set = false;
1083                 return docstring();
1084         }
1085
1086         if (!xsel_cache_.set ||
1087             cur.top() != xsel_cache_.cursor ||
1088             cur.anchor_.top() != xsel_cache_.anchor)
1089         {
1090                 xsel_cache_.cursor = cur.top();
1091                 xsel_cache_.anchor = cur.anchor_.top();
1092                 xsel_cache_.set = cur.selection();
1093                 return cur.selectionAsString(false);
1094         }
1095         return docstring();
1096 }
1097
1098
1099 void BufferView::clearSelection()
1100 {
1101         if (buffer_) {
1102                 cursor_.clearSelection();
1103                 // Clear the selection buffer. Otherwise a subsequent
1104                 // middle-mouse-button paste would use the selection buffer,
1105                 // not the more current external selection.
1106                 cap::clearSelection();
1107                 xsel_cache_.set = false;
1108                 // The buffer did not really change, but this causes the
1109                 // redraw we need because we cleared the selection above.
1110                 buffer_->changed();
1111         }
1112 }
1113
1114
1115 void BufferView::workAreaResize(int width, int height)
1116 {
1117         // Update from work area
1118         width_ = width;
1119         height_ = height;
1120
1121         // The complete text metrics will be redone.
1122         text_metrics_.clear();
1123
1124         if (buffer_)
1125                 resize();
1126 }
1127
1128
1129 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
1130 {
1131         pit_type pit = text.getPitNearY(*this, y);
1132         BOOST_ASSERT(pit != -1);
1133         Paragraph const & par = text.getPar(pit);
1134
1135         LYXERR(Debug::DEBUG)
1136                 << BOOST_CURRENT_FUNCTION
1137                 << ": x: " << x
1138                 << " y: " << y
1139                 << "  pit: " << pit
1140                 << endl;
1141         InsetList::const_iterator iit = par.insetlist.begin();
1142         InsetList::const_iterator iend = par.insetlist.end();
1143         for (; iit != iend; ++iit) {
1144                 Inset * const inset = iit->inset;
1145                 if (inset->covers(*this, x, y)) {
1146                         if (!inset->descendable())
1147                                 // No need to go further down if the inset is not 
1148                                 // descendable.
1149                                 return inset;
1150
1151                         size_t cell_number = inset->nargs();
1152                         // Check all the inner cell.
1153                         for (size_t i = 0; i != cell_number; ++i) {
1154                                 Text const * inner_text = inset->getText(i);
1155                                 if (inner_text) {
1156                                         // Try deeper.
1157                                         Inset const * inset_deeper = 
1158                                                 getCoveringInset(*inner_text, x, y);
1159                                         if (inset_deeper)
1160                                                 return inset_deeper;
1161                                 }
1162                         }
1163
1164                         LYXERR(Debug::DEBUG)
1165                                 << BOOST_CURRENT_FUNCTION
1166                                 << ": Hit inset: " << inset << endl;
1167                         return inset;
1168                 }
1169         }
1170         LYXERR(Debug::DEBUG)
1171                 << BOOST_CURRENT_FUNCTION
1172                 << ": No inset hit. " << endl;
1173         return 0;
1174 }
1175
1176
1177 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1178 {
1179         //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1180
1181         // This is only called for mouse related events including
1182         // LFUN_FILE_OPEN generated by drag-and-drop.
1183         FuncRequest cmd = cmd0;
1184
1185         // E.g. Qt mouse press when no buffer
1186         if (!buffer_)
1187                 return false;
1188
1189         Cursor cur(*this);
1190         cur.push(buffer_->inset());
1191         cur.selection() = cursor_.selection();
1192
1193         // Either the inset under the cursor or the
1194         // surrounding Text will handle this event.
1195
1196         // make sure we stay within the screen...
1197         cmd.y = min(max(cmd.y, -1), height_);
1198         
1199         if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1200                 
1201                 // Get inset under mouse, if there is one.
1202                 Inset const * covering_inset = 
1203                         getCoveringInset(buffer_->text(), cmd.x, cmd.y);
1204                 if (covering_inset == last_inset_)
1205                         // Same inset, no need to do anything...
1206                         return false;
1207
1208                 bool need_redraw = false;
1209                 // const_cast because of setMouseHover().
1210                 Inset * inset = const_cast<Inset *>(covering_inset);
1211                 if (last_inset_)
1212                         // Remove the hint on the last hovered inset (if any).
1213                         need_redraw |= last_inset_->setMouseHover(false);
1214                 if (inset)
1215                         // Highlighted the newly hovered inset (if any).
1216                         need_redraw |= inset->setMouseHover(true);
1217                 last_inset_ = inset;
1218
1219                 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1220                 // not expose the button for redraw. We adjust here the metrics dimension
1221                 // to enable a full redraw.
1222                 // FIXME: It is possible to redraw only the area around the button!
1223                 if (need_redraw 
1224                         && metrics_info_.update_strategy == SingleParUpdate) {
1225                         // FIXME: It should be possible to redraw only the area around 
1226                         // the button by doing this:
1227                         //
1228                         //metrics_info_.singlepar = false;
1229                         //metrics_info_.y1 = ymin of button;
1230                         //metrics_info_.y2 = ymax of button;
1231                         //
1232                         // Unfortunately, rowpainter.cpp:paintText() does not distinguish
1233                         // between background updates and text updates. So we use the hammer
1234                         // solution for now. We could also avoid the updateMetrics() below
1235                         // by using the first and last pit of the CoordCache. Have a look
1236                         // at Text::getPitNearY() to see what I mean.
1237                         //
1238                         //metrics_info_.pit1 = first pit of CoordCache;
1239                         //metrics_info_.pit2 = last pit of CoordCache;
1240                         //metrics_info_.singlepar = false;
1241                         //metrics_info_.y1 = 0;
1242                         //metrics_info_.y2 = height_;
1243                         //
1244                         updateMetrics(false);
1245                 }
1246
1247                 // This event (moving without mouse click) is not passed further.
1248                 // This should be changed if it is further utilized.
1249                 return need_redraw;
1250         }
1251         
1252         // Build temporary cursor.
1253         Inset * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1254
1255         // Put anchor at the same position.
1256         cur.resetAnchor();
1257
1258         // Try to dispatch to an non-editable inset near this position
1259         // via the temp cursor. If the inset wishes to change the real
1260         // cursor it has to do so explicitly by using
1261         //  cur.bv().cursor() = cur;  (or similar)
1262         if (inset) {
1263                 inset->dispatch(cur, cmd);
1264         }
1265
1266         // Now dispatch to the temporary cursor. If the real cursor should
1267         // be modified, the inset's dispatch has to do so explicitly.
1268         if (!cur.result().dispatched())
1269                 cur.dispatch(cmd);
1270
1271         // Redraw if requested and necessary.
1272         if (cur.result().dispatched() && cur.result().update())
1273                 return update(cur.result().update());
1274
1275         return false;
1276 }
1277
1278
1279 void BufferView::scroll(int /*lines*/)
1280 {
1281 //      if (!buffer_)
1282 //              return;
1283 //
1284 //      Text const * t = &buffer_->text();
1285 //      int const line_height = defaultRowHeight();
1286 //
1287 //      // The new absolute coordinate
1288 //      int new_top_y = top_y() + lines * line_height;
1289 //
1290 //      // Restrict to a valid value
1291 //      new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1292 //      new_top_y = std::max(0, new_top_y);
1293 //
1294 //      scrollDocView(new_top_y);
1295 //
1296 }
1297
1298
1299 void BufferView::setCursorFromRow(int row)
1300 {
1301         int tmpid = -1;
1302         int tmppos = -1;
1303
1304         buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1305
1306         if (tmpid == -1)
1307                 buffer_->text().setCursor(cursor_, 0, 0);
1308         else
1309                 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1310 }
1311
1312
1313 void BufferView::gotoLabel(docstring const & label)
1314 {
1315         for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1316                 vector<docstring> labels;
1317                 it->getLabelList(*buffer_, labels);
1318                 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1319                         setCursor(it);
1320                         update();
1321                         return;
1322                 }
1323         }
1324 }
1325
1326
1327 TextMetrics const & BufferView::textMetrics(Text const * t) const
1328 {
1329         return const_cast<BufferView *>(this)->textMetrics(t);
1330 }
1331
1332
1333 TextMetrics & BufferView::textMetrics(Text const * t)
1334 {
1335         TextMetricsCache::iterator tmc_it  = text_metrics_.find(t);
1336         if (tmc_it == text_metrics_.end()) {
1337                 tmc_it = text_metrics_.insert(
1338                         make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1339         }       
1340         return tmc_it->second;
1341 }
1342
1343
1344 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1345                 pit_type pit) const
1346 {
1347         return textMetrics(t).parMetrics(pit);
1348 }
1349
1350
1351 int BufferView::workHeight() const
1352 {
1353         return height_;
1354 }
1355
1356
1357 void BufferView::setCursor(DocIterator const & dit)
1358 {
1359         size_t const n = dit.depth();
1360         for (size_t i = 0; i < n; ++i)
1361                 dit[i].inset().edit(cursor_, true);
1362
1363         cursor_.setCursor(dit);
1364         cursor_.selection() = false;
1365 }
1366
1367
1368 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1369 {
1370         // Would be wrong to delete anything if we have a selection.
1371         if (cur.selection())
1372                 return false;
1373
1374         bool need_anchor_change = false;
1375         bool changed = cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1376                 need_anchor_change);
1377
1378         if (need_anchor_change)
1379                 cur.resetAnchor();
1380         
1381         if (!changed)
1382                 return false;
1383
1384         updateLabels(*buffer_);
1385
1386         updateMetrics(false);
1387         buffer_->changed();
1388         return true;
1389 }
1390
1391
1392 bool BufferView::mouseSetCursor(Cursor & cur)
1393 {
1394         BOOST_ASSERT(&cur.bv() == this);
1395
1396         // Has the cursor just left the inset?
1397         bool badcursor = false;
1398         bool leftinset = (&cursor_.inset() != &cur.inset());
1399         if (leftinset)
1400                 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1401
1402         // do the dEPM magic if needed
1403         // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1404         // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1405         // the leftinset bool would not be necessary (badcursor instead).
1406         bool update = leftinset;
1407         if (!badcursor && cursor_.inTexted())
1408                 update |= checkDepm(cur, cursor_);
1409
1410         // if the cursor was in an empty script inset and the new
1411         // position is in the nucleus of the inset, notifyCursorLeaves
1412         // will kill the script inset itself. So we check all the
1413         // elements of the cursor to make sure that they are correct.
1414         // For an example, see bug 2933: 
1415         // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1416         // The code below could maybe be moved to a DocIterator method.
1417         //lyxerr << "cur before " << cur <<std::endl;
1418         DocIterator dit(cur.inset());
1419         dit.push_back(cur.bottom());
1420         size_t i = 1;
1421         while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1422                 dit.push_back(cur[i]);
1423                 ++i;
1424         }
1425         //lyxerr << "5 cur after" << dit <<std::endl;
1426
1427         cursor_.setCursor(dit);
1428         cursor_.clearSelection();
1429         finishUndo();
1430         return update;
1431 }
1432
1433
1434 void BufferView::putSelectionAt(DocIterator const & cur,
1435                                 int length, bool backwards)
1436 {
1437         cursor_.clearSelection();
1438
1439         setCursor(cur);
1440
1441         if (length) {
1442                 if (backwards) {
1443                         cursor_.pos() += length;
1444                         cursor_.setSelection(cursor_, -length);
1445                 } else
1446                         cursor_.setSelection(cursor_, length);
1447                 cap::saveSelection(cursor_);
1448         }
1449 }
1450
1451
1452 Cursor & BufferView::cursor()
1453 {
1454         return cursor_;
1455 }
1456
1457
1458 Cursor const & BufferView::cursor() const
1459 {
1460         return cursor_;
1461 }
1462
1463
1464 pit_type BufferView::anchor_ref() const
1465 {
1466         return anchor_ref_;
1467 }
1468
1469
1470 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1471 {
1472         return metrics_info_;
1473 }
1474
1475
1476 // FIXME: We should split-up updateMetrics() for the singlepar case.
1477 void BufferView::updateMetrics(bool singlepar)
1478 {
1479         Text & buftext = buffer_->text();
1480         TextMetrics & tm = textMetrics(&buftext);
1481         pit_type size = int(buftext.paragraphs().size());
1482
1483         if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1484                 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1485                 offset_ref_ = 0;
1486         }
1487         
1488         // If the paragraph metrics has changed, we can not
1489         // use the singlepar optimisation.
1490         if (singlepar
1491                 // In Single Paragraph mode, rebreak only
1492                 // the (main text, not inset!) paragraph containing the cursor.
1493                 // (if this paragraph contains insets etc., rebreaking will
1494                 // recursively descend)
1495                 && tm.redoParagraph(cursor_.bottom().pit()))
1496                 singlepar = false;
1497
1498         pit_type const pit = anchor_ref_;
1499         int pit1 = pit;
1500         int pit2 = pit;
1501         size_t const npit = buftext.paragraphs().size();
1502
1503         // Rebreak anchor paragraph.
1504         if (!singlepar)
1505                 tm.redoParagraph(pit);
1506         
1507         // Clear out the position cache in case of full screen redraw.
1508         if (!singlepar)
1509                 coord_cache_.clear();
1510
1511         int y0 = tm.parMetrics(pit).ascent() - offset_ref_;
1512
1513         // Redo paragraphs above anchor if necessary.
1514         int y1 = y0;
1515         while (y1 > 0 && pit1 > 0) {
1516                 y1 -= tm.parMetrics(pit1).ascent();
1517                 --pit1;
1518                 if (!singlepar)
1519                         tm.redoParagraph(pit1);
1520                 y1 -= tm.parMetrics(pit1).descent();
1521         }
1522
1523
1524         // Take care of ascent of first line
1525         y1 -= tm.parMetrics(pit1).ascent();
1526
1527         // Normalize anchor for next time
1528         anchor_ref_ = pit1;
1529         offset_ref_ = -y1;
1530
1531         // Grey at the beginning is ugly
1532         if (pit1 == 0 && y1 > 0) {
1533                 y0 -= y1;
1534                 y1 = 0;
1535                 anchor_ref_ = 0;
1536         }
1537
1538         // Redo paragraphs below the anchor if necessary.
1539         int y2 = y0;
1540         while (y2 < height_ && pit2 < int(npit) - 1) {
1541                 y2 += tm.parMetrics(pit2).descent();
1542                 ++pit2;
1543                 if (!singlepar)
1544                         tm.redoParagraph(pit2);
1545                 y2 += tm.parMetrics(pit2).ascent();
1546         }
1547
1548         // Take care of descent of last line
1549         y2 += tm.parMetrics(pit2).descent();
1550
1551         // The coordinates of all these paragraphs are correct, cache them
1552         int y = y1;
1553         CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1554         for (pit_type pit = pit1; pit <= pit2; ++pit) {
1555                 ParagraphMetrics const & pm = tm.parMetrics(pit);
1556                 y += pm.ascent();
1557                 parPos[pit] = Point(0, y);
1558                 if (singlepar && pit == cursor_.bottom().pit()) {
1559                         // In Single Paragraph mode, collect here the
1560                         // y1 and y2 of the (one) paragraph the cursor is in
1561                         y1 = y - pm.ascent();
1562                         y2 = y + pm.descent();
1563                 }
1564                 y += pm.descent();
1565         }
1566
1567         if (singlepar) {
1568                 // collect cursor paragraph iter bounds
1569                 pit1 = cursor_.bottom().pit();
1570                 pit2 = cursor_.bottom().pit();
1571         }
1572
1573         LYXERR(Debug::DEBUG)
1574                 << BOOST_CURRENT_FUNCTION
1575                 << " y1: " << y1
1576                 << " y2: " << y2
1577                 << " pit1: " << pit1
1578                 << " pit2: " << pit2
1579                 << " npit: " << npit
1580                 << " singlepar: " << singlepar
1581                 << "size: " << size
1582                 << endl;
1583
1584         metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, 
1585                 singlepar? SingleParUpdate: FullScreenUpdate, size);
1586
1587         if (lyxerr.debugging(Debug::WORKAREA)) {
1588                 LYXERR(Debug::WORKAREA) << "BufferView::updateMetrics" << endl;
1589                 coord_cache_.dump();
1590         }
1591 }
1592
1593
1594 void BufferView::menuInsertLyXFile(string const & filenm)
1595 {
1596         BOOST_ASSERT(cursor_.inTexted());
1597         string filename = filenm;
1598
1599         if (filename.empty()) {
1600                 // Launch a file browser
1601                 // FIXME UNICODE
1602                 string initpath = lyxrc.document_path;
1603
1604                 if (buffer_) {
1605                         string const trypath = buffer_->filePath();
1606                         // If directory is writeable, use this as default.
1607                         if (isDirWriteable(FileName(trypath)))
1608                                 initpath = trypath;
1609                 }
1610
1611                 // FIXME UNICODE
1612                 FileDialog fileDlg(_("Select LyX document to insert"),
1613                         LFUN_FILE_INSERT,
1614                         make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1615                         make_pair(_("Examples|#E#e"), from_utf8(addPath(package().system_support().absFilename(), "examples"))));
1616
1617                 FileDialog::Result result =
1618                         fileDlg.open(from_utf8(initpath),
1619                                      FileFilterList(_("LyX Documents (*.lyx)")),
1620                                      docstring());
1621
1622                 if (result.first == FileDialog::Later)
1623                         return;
1624
1625                 // FIXME UNICODE
1626                 filename = to_utf8(result.second);
1627
1628                 // check selected filename
1629                 if (filename.empty()) {
1630                         // emit message signal.
1631                         message(_("Canceled."));
1632                         return;
1633                 }
1634         }
1635
1636         // Get absolute path of file and add ".lyx"
1637         // to the filename if necessary
1638         filename = fileSearch(string(), filename, "lyx").absFilename();
1639
1640         docstring const disp_fn = makeDisplayPath(filename);
1641         // emit message signal.
1642         message(bformat(_("Inserting document %1$s..."), disp_fn));
1643
1644         docstring res;
1645         Buffer buf("", false);
1646         if (lyx::loadLyXFile(&buf, FileName(filename))) {
1647                 ErrorList & el = buffer_->errorList("Parse");
1648                 // Copy the inserted document error list into the current buffer one.
1649                 el = buf.errorList("Parse");
1650                 recordUndo(cursor_);
1651                 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1652                                              buf.params().textclass, el);
1653                 res = _("Document %1$s inserted.");
1654         } else
1655                 res = _("Could not insert document %1$s");
1656
1657         // emit message signal.
1658         message(bformat(res, disp_fn));
1659         buffer_->errors("Parse");
1660         resize();
1661 }
1662
1663 } // namespace lyx