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