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