]> git.lyx.org Git - features.git/blob - src/insets/InsetText.cpp
Make InsetText store a Buffer.
[features.git] / src / insets / InsetText.cpp
1 /**
2  * \file InsetText.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Jürgen Vigna
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "InsetText.h"
14
15 #include "buffer_funcs.h"
16 #include "Buffer.h"
17 #include "BufferParams.h"
18 #include "BufferView.h"
19 #include "CompletionList.h"
20 #include "CoordCache.h"
21 #include "Cursor.h"
22 #include "CutAndPaste.h"
23 #include "DispatchResult.h"
24 #include "ErrorList.h"
25 #include "FuncRequest.h"
26 #include "InsetList.h"
27 #include "Intl.h"
28 #include "Lexer.h"
29 #include "lyxfind.h"
30 #include "LyXRC.h"
31 #include "MetricsInfo.h"
32 #include "output_docbook.h"
33 #include "output_latex.h"
34 #include "OutputParams.h"
35 #include "output_plaintext.h"
36 #include "paragraph_funcs.h"
37 #include "Paragraph.h"
38 #include "ParagraphParameters.h"
39 #include "ParIterator.h"
40 #include "Row.h"
41 #include "sgml.h"
42 #include "TexRow.h"
43 #include "TextClass.h"
44 #include "Text.h"
45 #include "TextMetrics.h"
46
47 #include "frontends/alert.h"
48 #include "frontends/Painter.h"
49
50 #include "support/debug.h"
51 #include "support/gettext.h"
52 #include "support/lstrings.h"
53
54 #include <boost/bind.hpp>
55 #include <boost/assert.hpp>
56
57 using namespace std;
58 using namespace lyx::support;
59
60 using boost::bind;
61 using boost::ref;
62
63 namespace lyx {
64
65 using graphics::PreviewLoader;
66
67
68 /////////////////////////////////////////////////////////////////////
69
70 InsetText::InsetText(Buffer const & buf)
71         : drawFrame_(false), frame_color_(Color_insetframe)
72 {
73         Inset::setBuffer(const_cast<Buffer &>(buf));
74         initParagraphs(buf);
75 }
76
77
78 InsetText::InsetText(InsetText const & in)
79         : Inset(in), text_()
80 {
81         text_.autoBreakRows_ = in.text_.autoBreakRows_;
82         drawFrame_ = in.drawFrame_;
83         frame_color_ = in.frame_color_;
84         text_.paragraphs() = in.text_.paragraphs();
85         setParagraphOwner();
86 }
87
88
89 void InsetText::initParagraphs(Buffer const & buf)
90 {
91         BOOST_ASSERT(paragraphs().empty());
92         buffer_ = const_cast<Buffer *>(&buf);
93         paragraphs().push_back(Paragraph());
94         Paragraph & ourpar = paragraphs().back();
95         ourpar.setEmptyOrDefaultLayout(buf.params().documentClass());
96         ourpar.setInsetOwner(this);
97 }
98
99 void InsetText::setParagraphOwner()
100 {
101         for_each(paragraphs().begin(), paragraphs().end(),
102                  bind(&Paragraph::setInsetOwner, _1, this));
103 }
104
105
106 void InsetText::clear()
107 {
108         ParagraphList & pars = paragraphs();
109         BOOST_ASSERT(!pars.empty());
110
111         // This is a gross hack...
112         Layout const & old_layout = pars.begin()->layout();
113
114         pars.clear();
115         pars.push_back(Paragraph());
116         pars.begin()->setInsetOwner(this);
117         pars.begin()->setLayout(old_layout);
118 }
119
120
121 Dimension const InsetText::dimension(BufferView const & bv) const
122 {
123         TextMetrics const & tm = bv.textMetrics(&text_);
124         Dimension dim = tm.dimension();
125         dim.wid += 2 * TEXT_TO_INSET_OFFSET;
126         dim.des += TEXT_TO_INSET_OFFSET;
127         dim.asc += TEXT_TO_INSET_OFFSET;
128         return dim;
129 }
130
131
132 void InsetText::write(ostream & os) const
133 {
134         os << "Text\n";
135         text_.write(buffer(), os);
136 }
137
138
139 void InsetText::read(Lexer & lex)
140 {
141         clear();
142
143         // delete the initial paragraph
144         Paragraph oldpar = *paragraphs().begin();
145         paragraphs().clear();
146         ErrorList errorList;
147         bool res = text_.read(buffer(), lex, errorList, this);
148
149         if (!res) {
150                 lex.printError("Missing \\end_inset at this point. "
151                                            "Read: `$$Token'");
152         }
153
154         // sanity check
155         // ensure we have at least one paragraph.
156         if (paragraphs().empty())
157                 paragraphs().push_back(oldpar);
158 }
159
160
161 void InsetText::metrics(MetricsInfo & mi, Dimension & dim) const
162 {
163         TextMetrics & tm = mi.base.bv->textMetrics(&text_);
164
165         //lyxerr << "InsetText::metrics: width: " << mi.base.textwidth << endl;
166
167         // Hand font through to contained lyxtext:
168         tm.font_.fontInfo() = mi.base.font;
169         mi.base.textwidth -= 2 * TEXT_TO_INSET_OFFSET;
170         if (hasFixedWidth())
171                 tm.metrics(mi, dim, mi.base.textwidth);
172         else
173                 tm.metrics(mi, dim);
174         mi.base.textwidth += 2 * TEXT_TO_INSET_OFFSET;
175         dim.asc += TEXT_TO_INSET_OFFSET;
176         dim.des += TEXT_TO_INSET_OFFSET;
177         dim.wid += 2 * TEXT_TO_INSET_OFFSET;
178 }
179
180
181 void InsetText::draw(PainterInfo & pi, int x, int y) const
182 {
183         TextMetrics & tm = pi.base.bv->textMetrics(&text_);
184
185         if (drawFrame_ || pi.full_repaint) {
186                 int const w = tm.width() + TEXT_TO_INSET_OFFSET;
187                 int const yframe = y - TEXT_TO_INSET_OFFSET - tm.ascent();
188                 int const h = tm.height() + 2 * TEXT_TO_INSET_OFFSET;
189                 int const xframe = x + TEXT_TO_INSET_OFFSET / 2;
190                 if (pi.full_repaint)
191                         pi.pain.fillRectangle(xframe, yframe, w, h, backgroundColor());
192                 if (drawFrame_)
193                         pi.pain.rectangle(xframe, yframe, w, h, frameColor());
194         }
195         tm.draw(pi, x + TEXT_TO_INSET_OFFSET, y);
196 }
197
198
199 docstring InsetText::editMessage() const
200 {
201         return _("Opened Text Inset");
202 }
203
204
205 void InsetText::edit(Cursor & cur, bool front, EntryDirection entry_from)
206 {
207         pit_type const pit = front ? 0 : paragraphs().size() - 1;
208         pos_type pos = front ? 0 : paragraphs().back().size();
209
210         // if visual information is not to be ignored, move to extreme right/left
211         if (entry_from != ENTRY_DIRECTION_IGNORE) {
212                 Cursor temp_cur = cur;
213                 temp_cur.pit() = pit;
214                 temp_cur.pos() = pos;
215                 temp_cur.posVisToRowExtremity(entry_from == ENTRY_DIRECTION_LEFT);
216                 pos = temp_cur.pos();
217         }
218
219         text_.setCursor(cur.top(), pit, pos);
220         cur.clearSelection();
221         cur.finishUndo();
222 }
223
224
225 Inset * InsetText::editXY(Cursor & cur, int x, int y)
226 {
227         return cur.bv().textMetrics(&text_).editXY(cur, x, y);
228 }
229
230
231 void InsetText::doDispatch(Cursor & cur, FuncRequest & cmd)
232 {
233         LYXERR(Debug::ACTION, "InsetText::doDispatch()"
234                 << " [ cmd.action = " << cmd.action << ']');
235         text_.dispatch(cur, cmd);
236 }
237
238
239 bool InsetText::getStatus(Cursor & cur, FuncRequest const & cmd,
240         FuncStatus & status) const
241 {
242         return text_.getStatus(cur, cmd, status);
243 }
244
245
246 void InsetText::setChange(Change const & change)
247 {
248         ParagraphList::iterator pit = paragraphs().begin();
249         ParagraphList::iterator end = paragraphs().end();
250         for (; pit != end; ++pit) {
251                 pit->setChange(change);
252         }
253 }
254
255
256 void InsetText::acceptChanges(BufferParams const & bparams)
257 {
258         text_.acceptChanges(bparams);
259 }
260
261
262 void InsetText::rejectChanges(BufferParams const & bparams)
263 {
264         text_.rejectChanges(bparams);
265 }
266
267
268 int InsetText::latex(odocstream & os, OutputParams const & runparams) const
269 {
270         TexRow texrow;
271         latexParagraphs(buffer(), text_, os, texrow, runparams);
272         return texrow.rows();
273 }
274
275
276 int InsetText::plaintext(odocstream & os, OutputParams const & runparams) const
277 {
278         ParagraphList::const_iterator beg = paragraphs().begin();
279         ParagraphList::const_iterator end = paragraphs().end();
280         ParagraphList::const_iterator it = beg;
281         bool ref_printed = false;
282         int len = 0;
283         for (; it != end; ++it) {
284                 if (it != beg) {
285                         os << '\n';
286                         if (runparams.linelen > 0)
287                                 os << '\n';
288                 }
289                 odocstringstream oss;
290                 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed);
291                 docstring const str = oss.str();
292                 os << str;
293                 // FIXME: len is not computed fully correctly; in principle,
294                 // we have to count the characters after the last '\n'
295                 len = str.size();
296         }
297
298         return len;
299 }
300
301
302 int InsetText::docbook(odocstream & os, OutputParams const & runparams) const
303 {
304         docbookParagraphs(paragraphs(), buffer(), os, runparams);
305         return 0;
306 }
307
308
309 void InsetText::validate(LaTeXFeatures & features) const
310 {
311         for_each(paragraphs().begin(), paragraphs().end(),
312                  bind(&Paragraph::validate, _1, ref(features)));
313 }
314
315
316 void InsetText::cursorPos(BufferView const & bv,
317                 CursorSlice const & sl, bool boundary, int & x, int & y) const
318 {
319         x = bv.textMetrics(&text_).cursorX(sl, boundary) + TEXT_TO_INSET_OFFSET;
320         y = bv.textMetrics(&text_).cursorY(sl, boundary);
321 }
322
323
324 bool InsetText::showInsetDialog(BufferView *) const
325 {
326         return false;
327 }
328
329
330 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
331 {
332         clear();
333         Paragraph & first = paragraphs().front();
334         for (unsigned int i = 0; i < data.length(); ++i)
335                 first.insertChar(i, data[i], font, trackChanges);
336 }
337
338
339 void InsetText::setAutoBreakRows(bool flag)
340 {
341         if (flag == text_.autoBreakRows_)
342                 return;
343
344         text_.autoBreakRows_ = flag;
345         if (flag)
346                 return;
347
348         // remove previously existing newlines
349         ParagraphList::iterator it = paragraphs().begin();
350         ParagraphList::iterator end = paragraphs().end();
351         for (; it != end; ++it)
352                 for (int i = 0; i < it->size(); ++i)
353                         if (it->isNewline(i))
354                                 // do not track the change, because the user
355                                 // is not allowed to revert/reject it
356                                 it->eraseChar(i, false);
357 }
358
359
360 void InsetText::setDrawFrame(bool flag)
361 {
362         drawFrame_ = flag;
363 }
364
365
366 ColorCode InsetText::frameColor() const
367 {
368         return frame_color_;
369 }
370
371
372 void InsetText::setFrameColor(ColorCode col)
373 {
374         frame_color_ = col;
375 }
376
377
378 void InsetText::appendParagraphs(ParagraphList & plist)
379 {
380         // There is little we can do here to keep track of changes.
381         // As of 2006/10/20, appendParagraphs is used exclusively by
382         // LyXTabular::setMultiColumn. In this context, the paragraph break
383         // is lost irreversibly and the appended text doesn't really change
384
385         ParagraphList & pl = paragraphs();
386
387         ParagraphList::iterator pit = plist.begin();
388         ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
389         ++pit;
390         mergeParagraph(buffer().params(), pl,
391                        distance(pl.begin(), ins) - 1);
392
393         for_each(pit, plist.end(),
394                  bind(&ParagraphList::push_back, ref(pl), _1));
395 }
396
397
398 void InsetText::addPreview(PreviewLoader & loader) const
399 {
400         ParagraphList::const_iterator pit = paragraphs().begin();
401         ParagraphList::const_iterator pend = paragraphs().end();
402
403         for (; pit != pend; ++pit) {
404                 InsetList::const_iterator it  = pit->insetList().begin();
405                 InsetList::const_iterator end = pit->insetList().end();
406                 for (; it != end; ++it)
407                         it->inset->addPreview(loader);
408         }
409 }
410
411
412 ParagraphList const & InsetText::paragraphs() const
413 {
414         return text_.paragraphs();
415 }
416
417
418 ParagraphList & InsetText::paragraphs()
419 {
420         return text_.paragraphs();
421 }
422
423
424 //void InsetInclude::addToToc(ParConstIterator const & cpit) const
425 //{
426 //}
427
428
429 void InsetText::updateLabels(ParIterator const & it)
430 {
431         ParIterator it2 = it;
432         it2.forwardPos();
433         BOOST_ASSERT(&it2.inset() == this && it2.pit() == 0);
434         lyx::updateLabels(buffer(), it2);
435 }
436
437
438 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
439 {
440         if (cur.buffer().isClean())
441                 return Inset::notifyCursorLeaves(old, cur);
442         
443         // find text inset in old cursor
444         Cursor insetCur = old;
445         int scriptSlice = insetCur.find(this);
446         BOOST_ASSERT(scriptSlice != -1);
447         insetCur.cutOff(scriptSlice);
448         BOOST_ASSERT(&insetCur.inset() == this);
449         
450         // update the old paragraph's words
451         insetCur.paragraph().updateWords(insetCur.top());
452         
453         return Inset::notifyCursorLeaves(old, cur);
454 }
455
456
457 bool InsetText::completionSupported(Cursor const & cur) const
458 {
459         Cursor const & bvCur = cur.bv().cursor();
460         if (&bvCur.inset() != this)
461                 return false;
462         return text_.completionSupported(cur);
463 }
464
465
466 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
467 {
468         return completionSupported(cur);
469 }
470
471
472 bool InsetText::automaticInlineCompletion() const
473 {
474         return lyxrc.completion_inline_text;
475 }
476
477
478 bool InsetText::automaticPopupCompletion() const
479 {
480         return lyxrc.completion_popup_text;
481 }
482
483
484 bool InsetText::showCompletionCursor() const
485 {
486         return lyxrc.completion_cursor_text;
487 }
488
489
490 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
491 {
492         return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
493 }
494
495
496 docstring InsetText::completionPrefix(Cursor const & cur) const
497 {
498         if (!completionSupported(cur))
499                 return docstring();
500         return text_.completionPrefix(cur);
501 }
502
503
504 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
505         bool finished)
506 {
507         if (!completionSupported(cur))
508                 return false;
509
510         return text_.insertCompletion(cur, s, finished);
511 }
512
513
514 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y, 
515         Dimension & dim) const
516 {
517         TextMetrics const & tm = cur.bv().textMetrics(&text_);
518         tm.completionPosAndDim(cur, x, y, dim);
519 }
520
521
522 docstring InsetText::contextMenu(BufferView const &, int, int) const
523 {
524         return from_ascii("context-edit");
525 }
526
527
528 } // namespace lyx