3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alfredo Braunstein
7 * \author Lars Gullik Bjønnes
10 * \author Jürgen Vigna
12 * Full author contact details are available in file CREDITS.
17 #include "BufferView.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"
27 #include "DispatchResult.h"
28 #include "ErrorList.h"
30 #include "FloatList.h"
31 #include "FuncRequest.h"
32 #include "FuncStatus.h"
35 #include "InsetIterator.h"
37 #include "LaTeXFeatures.h"
38 #include "callback.h" // added for Dispatch functions
44 #include "TextClass.h"
47 #include "Paragraph.h"
48 #include "paragraph_funcs.h"
49 #include "ParagraphParameters.h"
50 #include "ParIterator.h"
55 #include "WordLangTuple.h"
56 #include "MetricsInfo.h"
58 #include "insets/InsetBibtex.h"
59 #include "insets/InsetCommand.h" // ChangeRefs
60 #include "insets/InsetRef.h"
61 #include "insets/InsetText.h"
63 #include "frontends/alert.h"
64 #include "frontends/FileDialog.h"
65 #include "frontends/FontMetrics.h"
67 #include "graphics/Previews.h"
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"
75 #include <boost/bind.hpp>
76 #include <boost/current_function.hpp>
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;
96 using std::istringstream;
100 using std::mem_fun_ref;
104 namespace Alert = frontend::Alert;
108 /// Return an inset of this class if it exists at the current cursor position
110 T * getInsetByCode(Cursor & cur, Inset::Code code)
113 DocIterator it = cur;
114 if (it.nextInset() &&
115 it.nextInset()->lyxCode() == code) {
116 inset = static_cast<T*>(it.nextInset());
124 BufferView::BufferView()
125 : width_(0), height_(0), buffer_(0), wh_(0),
127 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
128 intl_(new Intl), last_inset_(0)
130 xsel_cache_.set = false;
131 intl_->initKeyMapper(lyxrc.use_kbmap);
135 BufferView::~BufferView()
140 Buffer * BufferView::buffer() const
146 void BufferView::setBuffer(Buffer * b)
148 LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
149 << "[ b = " << b << "]" << endl;
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())
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
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);
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()) );
182 // If we're quitting lyx, don't bother updating stuff
188 //FIXME Fix for bug 3440 is here.
189 // If we are closing current buffer, switch to the first in
192 LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
193 << " No Buffer!" << endl;
194 // We are closing the buffer, use the first buffer as current
196 // if (last_buffer_) buffer_ = last_buffer_;
197 // also check that this is in theBufferList()?
198 buffer_ = theBufferList().first();
201 // last_buffer = buffer_;
202 // Set current buffer
207 cursor_ = Cursor(*this);
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_);
220 // Update the metrics now that we have a proper Cursor.
221 updateMetrics(false);
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)
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.
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();
240 // Update the metrics if the cursor new position was off screen.
241 updateMetrics(false);
244 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
245 graphics::Previews::get().generateBufferPreviews(*buffer_);
249 void BufferView::resize()
254 LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION << endl;
256 updateMetrics(false);
260 bool BufferView::fitCursor()
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_)
276 bool BufferView::multiParSel()
278 if (!cursor_.selection())
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_;
287 bool BufferView::update(Update::flags flags)
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.
293 // This is close to a hot-path.
295 << BOOST_CURRENT_FUNCTION
296 << "[fitcursor = " << (flags & Update::FitCursor)
297 << ", forceupdate = " << (flags & Update::Force)
298 << ", singlepar = " << (flags & Update::SinglePar)
299 << "] buffer: " << buffer_ << endl;
301 // Check needed to survive LyX startup
305 LYXERR(Debug::WORKAREA) << "BufferView::update" << std::endl;
307 // Update macro store
308 if (!(cursor().inMathed() && cursor().inMacroMode()))
309 buffer_->buildMacros();
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.
315 // Case when no explicit update is requested.
317 // no need to redraw anything.
318 metrics_info_.update_strategy = NoScreenUpdate;
322 if (flags == Update::Decoration) {
323 metrics_info_.update_strategy = DecorationUpdate;
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.
332 updateMetrics(false);
335 if (flags & Update::Decoration) {
336 metrics_info_.update_strategy = DecorationUpdate;
339 // no screen update is needed.
340 metrics_info_.update_strategy = NoScreenUpdate;
344 bool full_metrics = flags & Update::Force;
345 if (flags & Update::MultiParSel)
346 full_metrics |= multiParSel();
348 bool const single_par = !full_metrics;
349 updateMetrics(single_par);
351 if (flags & Update::FitCursor && fitCursor())
352 updateMetrics(false);
354 // tell the frontend to update the screen.
359 void BufferView::updateScrollbar()
362 LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION
363 << " no text in updateScrollbar" << endl;
364 scrollbarParameters_.reset();
368 Text & t = buffer_->text();
369 TextMetrics & tm = text_metrics_[&t];
371 int const parsize = int(t.paragraphs().size() - 1);
372 if (anchor_ref_ > parsize) {
373 anchor_ref_ = parsize;
378 << BOOST_CURRENT_FUNCTION
379 << " Updating scrollbar: height: " << t.paragraphs().size()
380 << " curr par: " << cursor_.bottom().pit()
381 << " default height " << defaultRowHeight() << endl;
383 // It would be better to fix the scrollbar to understand
384 // values in [0..1] and divide everything by wh
386 // estimated average paragraph height:
390 int h = tm.parMetrics(anchor_ref_).height();
392 // Normalize anchor/offset (MV):
393 while (offset_ref_ > h && anchor_ref_ < parsize) {
396 h = tm.parMetrics(anchor_ref_).height();
398 // Look at paragraph heights on-screen
401 for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
404 int const h2 = tm.parMetrics(pit).height();
410 int const hav = sumh / nh;
411 // More realistic average paragraph height
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));
422 ScrollbarParameters const & BufferView::scrollbarParameters() const
424 return scrollbarParameters_;
428 void BufferView::scrollDocView(int value)
430 LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
431 << "[ value = " << value << "]" << endl;
436 Text & t = buffer_->text();
437 TextMetrics & tm = text_metrics_[&t];
439 float const bar = value / float(wh_ * t.paragraphs().size());
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;
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);
452 void BufferView::setCursorFromScrollbar()
457 Text & t = buffer_->text();
459 int const height = 2 * defaultRowHeight();
460 int const first = height;
461 int const last = height_ - height;
462 Cursor & cur = cursor_;
464 bv_funcs::CurStatus st = bv_funcs::status(this, cur);
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();
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();
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));
485 cur.reset(buffer_->inset());
486 t.setCursorFromCoordinates(cur, 0, newy);
492 Change const BufferView::getCurrentChange() const
494 if (!cursor_.selection())
495 return Change(Change::UNCHANGED);
497 DocIterator dit = cursor_.selectionBegin();
498 return dit.paragraph().lookupChange(dit.pos());
502 void BufferView::saveBookmark(unsigned int idx)
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
508 LyX::ref().session().bookmarks().save(
509 FileName(buffer_->fileName()),
510 cursor_.bottom().pit(),
511 cursor_.bottom().pos(),
512 cursor_.paragraph().id(),
517 // emit message signal.
518 message(_("Save bookmark"));
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)
525 cursor_.clearSelection();
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.
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
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) {
547 // Note: return bottom (document) level pit.
548 return boost::make_tuple(cursor_.bottom().pit(), cursor_.bottom().pos(), top_id);
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
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());
562 return boost::make_tuple(it.pit(), it.pos(),
563 it.paragraph().id());
566 return boost::make_tuple(pit_type(0), pos_type(0), 0);
570 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
572 if (lyxrc.rtl_support) {
573 if (cursor_.innerText()->real_current_font.isRightToLeft()) {
574 if (intl_->keymap == Intl::PRIMARY)
577 if (intl_->keymap == Intl::SECONDARY)
582 intl_->getTransManager().translateAndInsert(c, t, cur);
586 int BufferView::workWidth() const
592 void BufferView::center()
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);
600 offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
601 + pm.ascent() - height_ / 2;
605 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
609 Cursor & cur = cursor_;
611 switch (cmd.action) {
614 flag.enabled(!buffer_->undostack().empty());
617 flag.enabled(!buffer_->redostack().empty());
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());
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:
635 case LFUN_REFERENCE_NEXT:
637 case LFUN_WORD_REPLACE:
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:
649 case LFUN_LABEL_GOTO: {
650 flag.enabled(!cmd.argument().empty()
651 || getInsetByCode<InsetRef>(cur, Inset::REF_CODE));
655 case LFUN_CHANGES_TRACK:
657 flag.setOnOff(buffer_->params().trackChanges);
660 case LFUN_CHANGES_OUTPUT:
661 flag.enabled(buffer_);
662 flag.setOnOff(buffer_->params().outputChanges);
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_);
676 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
677 flag.setOnOff(buffer_->params().compressed);
689 Update::flags BufferView::dispatch(FuncRequest const & cmd)
691 //lyxerr << BOOST_CURRENT_FUNCTION
692 // << [ cmd = " << cmd << "]" << endl;
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() << ']'
703 // FIXME: this should not be possible.
707 Cursor & cur = cursor_;
708 // Default Update flags.
709 Update::flags updateFlags = Update::Force | Update::FitCursor;
711 switch (cmd.action) {
714 cur.message(_("Undo"));
715 cur.clearSelection();
716 if (!textUndo(*this)) {
717 cur.message(_("No further undo information"));
718 updateFlags = Update::None;
723 cur.message(_("Redo"));
724 cur.clearSelection();
725 if (!textRedo(*this)) {
726 cur.message(_("No further redo information"));
727 updateFlags = Update::None;
731 case LFUN_FILE_INSERT:
733 menuInsertLyXFile(to_utf8(cmd.argument()));
736 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
738 insertPlaintextFile(this, to_utf8(cmd.argument()), true);
741 case LFUN_FILE_INSERT_PLAINTEXT:
743 insertPlaintextFile(this, to_utf8(cmd.argument()), false);
746 case LFUN_FONT_STATE:
747 cur.message(cur.currentState());
750 case LFUN_BOOKMARK_SAVE:
751 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
754 case LFUN_LABEL_GOTO: {
755 docstring label = cmd.argument();
758 getInsetByCode<InsetRef>(cursor_,
761 label = inset->getParam("reference");
762 // persistent=false: use temp_bookmark
772 case LFUN_PARAGRAPH_GOTO: {
773 int const id = convert<int>(to_utf8(cmd.argument()));
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()) {
779 << "No matching paragraph found! ["
780 << id << "]." << endl;
783 << "Paragraph " << par->id()
784 << " found in buffer `"
785 << b->fileName() << "'." << endl;
789 setCursor(makeDocIterator(par, 0));
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;
804 case LFUN_OUTLINE_UP:
805 toc::outline(toc::Up, cursor_);
806 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
807 updateLabels(*buffer_);
809 case LFUN_OUTLINE_DOWN:
810 toc::outline(toc::Down, cursor_);
811 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
812 updateLabels(*buffer_);
814 case LFUN_OUTLINE_IN:
815 toc::outline(toc::In, cursor_);
816 updateLabels(*buffer_);
818 case LFUN_OUTLINE_OUT:
819 toc::outline(toc::Out, cursor_);
820 updateLabels(*buffer_);
824 bv_funcs::gotoInset(this, Inset::NOTE_CODE, false);
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);
835 case LFUN_CHANGES_TRACK:
836 buffer_->params().trackChanges = !buffer_->params().trackChanges;
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");
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."));
862 case LFUN_CHANGE_NEXT:
863 findNextChange(this);
866 case LFUN_CHANGES_MERGE:
867 if (findNextChange(this))
868 showDialog("changes");
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);
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);
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))
906 replace(this, cmd, has_deleted);
911 cur.clearSelection();
913 cur.message(from_utf8(N_("Mark off")));
917 cur.clearSelection();
920 cur.message(from_utf8(N_("Mark on")));
923 case LFUN_MARK_TOGGLE:
924 cur.clearSelection();
927 cur.message(from_utf8(N_("Mark removed")));
930 cur.message(from_utf8(N_("Mark set")));
935 case LFUN_SCREEN_RECENTER:
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,
945 if (inset->addDatabase(to_utf8(cmd.argument())))
946 buffer_->updateBibfilesCache();
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,
957 if (inset->delDatabase(to_utf8(cmd.argument())))
958 buffer_->updateBibfilesCache();
963 case LFUN_WORDS_COUNT: {
964 DocIterator from, to;
965 if (cur.selection()) {
966 from = cur.selectionBegin();
967 to = cur.selectionEnd();
969 from = doc_iterator_begin(buffer_->inset());
970 to = doc_iterator_end(buffer_->inset());
972 int const count = countWords(from, to);
976 message = bformat(_("%1$d words in selection."),
979 message = bformat(_("%1$d words in document."),
984 message = _("One word in selection.");
986 message = _("One word in document.");
989 Alert::information(_("Count words"), message);
993 case LFUN_BUFFER_TOGGLE_COMPRESSION:
994 // turn compression on/off
995 buffer_->params().compressed = !buffer_->params().compressed;
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
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()) {
1012 // if it did not work, try the underlying inset.
1013 if (!cur.result().dispatched())
1014 cur.dispatch(tmpcmd);
1016 if (cur.result().dispatched())
1017 cur.clearSelection();
1023 updateFlags = Update::None;
1030 docstring const BufferView::requestSelection()
1035 Cursor & cur = cursor_;
1037 if (!cur.selection()) {
1038 xsel_cache_.set = false;
1042 if (!xsel_cache_.set ||
1043 cur.top() != xsel_cache_.cursor ||
1044 cur.anchor_.top() != xsel_cache_.anchor)
1046 xsel_cache_.cursor = cur.top();
1047 xsel_cache_.anchor = cur.anchor_.top();
1048 xsel_cache_.set = cur.selection();
1049 return cur.selectionAsString(false);
1055 void BufferView::clearSelection()
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.
1071 void BufferView::workAreaResize(int width, int height)
1073 // Update from work area
1077 // The complete text metrics will be redone.
1078 text_metrics_.clear();
1085 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
1087 pit_type pit = text.getPitNearY(*this, y);
1088 BOOST_ASSERT(pit != -1);
1089 Paragraph const & par = text.getPar(pit);
1091 LYXERR(Debug::DEBUG)
1092 << BOOST_CURRENT_FUNCTION
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
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);
1113 Inset const * inset_deeper =
1114 getCoveringInset(*inner_text, x, y);
1116 return inset_deeper;
1120 LYXERR(Debug::DEBUG)
1121 << BOOST_CURRENT_FUNCTION
1122 << ": Hit inset: " << inset << endl;
1126 LYXERR(Debug::DEBUG)
1127 << BOOST_CURRENT_FUNCTION
1128 << ": No inset hit. " << endl;
1133 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1135 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1137 // This is only called for mouse related events including
1138 // LFUN_FILE_OPEN generated by drag-and-drop.
1139 FuncRequest cmd = cmd0;
1141 // E.g. Qt mouse press when no buffer
1146 cur.push(buffer_->inset());
1147 cur.selection() = cursor_.selection();
1149 // Either the inset under the cursor or the
1150 // surrounding Text will handle this event.
1152 // make sure we stay within the screen...
1153 cmd.y = min(max(cmd.y, -1), height_);
1155 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
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...
1164 bool need_redraw = false;
1165 // const_cast because of setMouseHover().
1166 Inset * inset = const_cast<Inset *>(covering_inset);
1168 // Remove the hint on the last hovered inset (if any).
1169 need_redraw |= last_inset_->setMouseHover(false);
1171 // Highlighted the newly hovered inset (if any).
1172 need_redraw |= inset->setMouseHover(true);
1173 last_inset_ = inset;
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!
1180 && metrics_info_.update_strategy == SingleParUpdate) {
1181 // FIXME: It should be possible to redraw only the area around
1182 // the button by doing this:
1184 //metrics_info_.singlepar = false;
1185 //metrics_info_.y1 = ymin of button;
1186 //metrics_info_.y2 = ymax of button;
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.
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_;
1200 updateMetrics(false);
1203 // This event (moving without mouse click) is not passed further.
1204 // This should be changed if it is further utilized.
1208 // Build temporary cursor.
1209 Inset * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1211 // Put anchor at the same position.
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)
1219 inset->dispatch(cur, cmd);
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())
1227 // Redraw if requested and necessary.
1228 if (cur.result().dispatched() && cur.result().update())
1229 return update(cur.result().update());
1235 void BufferView::scroll(int /*lines*/)
1240 // Text const * t = &buffer_->text();
1241 // int const line_height = defaultRowHeight();
1243 // // The new absolute coordinate
1244 // int new_top_y = top_y() + lines * line_height;
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);
1250 // scrollDocView(new_top_y);
1255 void BufferView::setCursorFromRow(int row)
1260 buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1262 cursor_.reset(buffer_->inset());
1264 buffer_->text().setCursor(cursor_, 0, 0);
1266 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1270 void BufferView::gotoLabel(docstring const & label)
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()) {
1284 TextMetrics const & BufferView::textMetrics(Text const * t) const
1286 return const_cast<BufferView *>(this)->textMetrics(t);
1290 TextMetrics & BufferView::textMetrics(Text const * t)
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;
1297 return tmc_it->second;
1301 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1304 return textMetrics(t).parMetrics(pit);
1308 int BufferView::workHeight() const
1314 void BufferView::setCursor(DocIterator const & dit)
1316 size_t const n = dit.depth();
1317 for (size_t i = 0; i < n; ++i)
1318 dit[i].inset().edit(cursor_, true);
1320 cursor_.setCursor(dit);
1321 cursor_.selection() = false;
1325 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1327 // Would be wrong to delete anything if we have a selection.
1328 if (cur.selection())
1331 bool need_anchor_change = false;
1332 bool changed = cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1333 need_anchor_change);
1335 if (need_anchor_change)
1341 updateLabels(*buffer_);
1343 updateMetrics(false);
1349 bool BufferView::mouseSetCursor(Cursor & cur)
1351 BOOST_ASSERT(&cur.bv() == this);
1353 // this event will clear selection so we save selection for
1354 // persistent selection
1355 cap::saveSelection(cursor());
1357 // Has the cursor just left the inset?
1358 bool badcursor = false;
1359 bool leftinset = (&cursor_.inset() != &cur.inset());
1361 badcursor = notifyCursorLeaves(cursor_, cur);
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_);
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());
1382 while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1383 dit.push_back(cur[i]);
1386 //lyxerr << "5 cur after" << dit <<std::endl;
1388 cursor_.setCursor(dit);
1389 cursor_.boundary(cur.boundary());
1390 cursor_.clearSelection();
1396 void BufferView::putSelectionAt(DocIterator const & cur,
1397 int length, bool backwards)
1399 cursor_.clearSelection();
1405 cursor_.pos() += length;
1406 cursor_.setSelection(cursor_, -length);
1408 cursor_.setSelection(cursor_, length);
1413 Cursor & BufferView::cursor()
1419 Cursor const & BufferView::cursor() const
1425 pit_type BufferView::anchor_ref() const
1431 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1433 return metrics_info_;
1437 // FIXME: We should split-up updateMetrics() for the singlepar case.
1438 void BufferView::updateMetrics(bool singlepar)
1440 Text & buftext = buffer_->text();
1441 TextMetrics & tm = textMetrics(&buftext);
1442 pit_type size = int(buftext.paragraphs().size());
1444 if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1445 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1450 // Clear out the position cache in case of full screen redraw,
1451 coord_cache_.clear();
1453 // Clear out paragraph metrics to avoid having invalid metrics
1454 // in the cache from paragraphs not relayouted below
1458 // If the paragraph metrics has changed, we can not
1459 // use the singlepar optimisation.
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()))
1468 pit_type const pit = anchor_ref_;
1471 size_t const npit = buftext.paragraphs().size();
1473 // Rebreak anchor paragraph.
1475 tm.redoParagraph(pit);
1477 int y0 = tm.parMetrics(pit).ascent() - offset_ref_;
1479 // Redo paragraphs above anchor if necessary.
1481 while (y1 > 0 && pit1 > 0) {
1482 y1 -= tm.parMetrics(pit1).ascent();
1485 tm.redoParagraph(pit1);
1486 y1 -= tm.parMetrics(pit1).descent();
1490 // Take care of ascent of first line
1491 y1 -= tm.parMetrics(pit1).ascent();
1493 // Normalize anchor for next time
1497 // Grey at the beginning is ugly
1498 if (pit1 == 0 && y1 > 0) {
1504 // Redo paragraphs below the anchor if necessary.
1506 while (y2 < height_ && pit2 < int(npit) - 1) {
1507 y2 += tm.parMetrics(pit2).descent();
1510 tm.redoParagraph(pit2);
1511 y2 += tm.parMetrics(pit2).ascent();
1514 // Take care of descent of last line
1515 y2 += tm.parMetrics(pit2).descent();
1517 // The coordinates of all these paragraphs are correct, cache them
1519 CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1520 for (pit_type pit = pit1; pit <= pit2; ++pit) {
1521 ParagraphMetrics const & pm = tm.parMetrics(pit);
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();
1534 // collect cursor paragraph iter bounds
1535 pit1 = cursor_.bottom().pit();
1536 pit2 = cursor_.bottom().pit();
1539 LYXERR(Debug::DEBUG)
1540 << BOOST_CURRENT_FUNCTION
1543 << " pit1: " << pit1
1544 << " pit2: " << pit2
1545 << " npit: " << npit
1546 << " singlepar: " << singlepar
1550 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2,
1551 singlepar? SingleParUpdate: FullScreenUpdate, size);
1553 if (lyxerr.debugging(Debug::WORKAREA)) {
1554 LYXERR(Debug::WORKAREA) << "BufferView::updateMetrics" << endl;
1555 coord_cache_.dump();
1560 void BufferView::menuInsertLyXFile(string const & filenm)
1562 BOOST_ASSERT(cursor_.inTexted());
1563 string filename = filenm;
1565 if (filename.empty()) {
1566 // Launch a file browser
1568 string initpath = lyxrc.document_path;
1571 string const trypath = buffer_->filePath();
1572 // If directory is writeable, use this as default.
1573 if (isDirWriteable(FileName(trypath)))
1578 FileDialog fileDlg(_("Select LyX document to 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(),
1585 FileDialog::Result result =
1586 fileDlg.open(from_utf8(initpath),
1587 FileFilterList(_("LyX Documents (*.lyx)")),
1590 if (result.first == FileDialog::Later)
1594 filename = to_utf8(result.second);
1596 // check selected filename
1597 if (filename.empty()) {
1598 // emit message signal.
1599 message(_("Canceled."));
1604 // Get absolute path of file and add ".lyx"
1605 // to the filename if necessary
1606 filename = fileSearch(string(), filename, "lyx").absFilename();
1608 docstring const disp_fn = makeDisplayPath(filename);
1609 // emit message signal.
1610 message(bformat(_("Inserting document %1$s..."), disp_fn));
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.");
1623 res = _("Could not insert document %1$s");
1625 // emit message signal.
1626 message(bformat(res, disp_fn));
1627 buffer_->errors("Parse");