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