2 * \file buffer_funcs.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Alfredo Braunstein
9 * Full author contact details are available in file CREDITS.
15 #include "buffer_funcs.h"
17 #include "BufferList.h"
18 #include "BufferParams.h"
19 #include "DocIterator.h"
21 #include "ErrorList.h"
23 #include "FloatList.h"
24 #include "InsetList.h"
25 #include "InsetIterator.h"
29 #include "LayoutPtr.h"
31 #include "TextClass.h"
32 #include "TextClassList.h"
33 #include "Paragraph.h"
34 #include "paragraph_funcs.h"
35 #include "ParagraphList.h"
36 #include "ParagraphParameters.h"
37 #include "ParIterator.h"
40 #include "TocBackend.h"
42 #include "frontends/alert.h"
44 #include "insets/InsetBibitem.h"
45 #include "insets/InsetInclude.h"
47 #include "support/convert.h"
48 #include "support/debug.h"
49 #include "support/filetools.h"
50 #include "support/gettext.h"
51 #include "support/lstrings.h"
52 #include "support/textutils.h"
55 using namespace lyx::support;
59 namespace Alert = frontend::Alert;
62 Buffer * checkAndLoadLyXFile(FileName const & filename)
65 Buffer * checkBuffer = theBufferList().getBuffer(filename.absFilename());
67 if (checkBuffer->isClean())
69 docstring const file = makeDisplayPath(filename.absFilename(), 20);
70 docstring text = bformat(_(
71 "The document %1$s is already loaded and has unsaved changes.\n"
72 "Do you want to abandon your changes and reload the version on disk?"), file);
73 if (Alert::prompt(_("Reload saved document?"),
74 text, 0, 1, _("&Reload"), _("&Keep Changes")))
77 // FIXME: should be LFUN_REVERT
78 theBufferList().release(checkBuffer);
80 return checkAndLoadLyXFile(filename);
83 if (filename.exists()) {
84 if (!filename.isReadableFile()) {
85 docstring text = bformat(_("The file %1$s exists but is not "
86 "readable by the current user."),
87 from_utf8(filename.absFilename()));
88 Alert::error(_("File not readable!"), text);
91 Buffer * b = theBufferList().newBuffer(filename.absFilename());
93 // Buffer creation is not possible.
95 if (!b->loadLyXFile(filename)) {
96 theBufferList().release(b);
102 docstring text = bformat(_("The document %1$s does not yet "
103 "exist.\n\nDo you want to create a new document?"),
104 from_utf8(filename.absFilename()));
105 if (!Alert::prompt(_("Create new document?"),
106 text, 0, 1, _("&Create"), _("Cancel")))
107 return newFile(filename.absFilename(), string(), true);
113 // FIXME newFile() should probably be a member method of Application...
114 Buffer * newFile(string const & filename, string const & templatename,
118 Buffer * b = theBufferList().newBuffer(filename);
120 // Buffer creation is not possible.
124 // use defaults.lyx as a default template if it exists.
125 if (templatename.empty())
126 tname = libFileSearch("templates", "defaults.lyx");
128 tname = makeAbsPath(templatename);
130 if (!tname.empty()) {
131 if (!b->readFile(tname)) {
132 docstring const file = makeDisplayPath(tname.absFilename(), 50);
133 docstring const text = bformat(
134 _("The specified document template\n%1$s\ncould not be read."),
136 Alert::error(_("Could not read template"), text);
137 theBufferList().release(b);
144 b->setFileName(filename);
147 b->setReadonly(false);
148 b->setFullyLoaded(true);
154 Buffer * newUnnamedFile(string const & templatename, FileName const & path)
156 static int newfile_number;
158 string document_path = path.absFilename();
159 string filename = addName(document_path,
160 "newfile" + convert<string>(++newfile_number) + ".lyx");
161 while (theBufferList().exists(filename)
162 || FileName(filename).isReadableFile()) {
164 filename = addName(document_path,
165 "newfile" + convert<string>(newfile_number) + ".lyx");
167 return newFile(filename, templatename, false);
171 int countWords(DocIterator const & from, DocIterator const & to)
175 for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
176 // Copied and adapted from isLetter() in ControlSpellChecker
178 && dit.pos() != dit.lastpos()
179 && dit.paragraph().isLetter(dit.pos())
180 && !dit.paragraph().isDeleted(dit.pos())) {
193 int countChars(DocIterator const & from, DocIterator const & to, bool with_blanks)
197 for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
199 if (!dit.inTexted()) continue;
200 Paragraph const & par = dit.paragraph();
201 pos_type const pos = dit.pos();
203 if (pos != dit.lastpos() && !par.isDeleted(pos)) {
204 if (par.isInset(pos)) {
205 Inset const * ins = par.getInset(pos);
208 else if (with_blanks && ins->isSpace())
211 char_type const c = par.getChar(pos);
212 if (isPrintableNonspace(c))
214 else if (isSpace(c) && with_blanks)
220 return chars + blanks;
226 depth_type getDepth(DocIterator const & it)
228 depth_type depth = 0;
229 for (size_t i = 0 ; i < it.depth() ; ++i)
230 if (!it[i].inset().inMathed())
231 depth += it[i].paragraph().getDepth() + 1;
232 // remove 1 since the outer inset does not count
236 depth_type getItemDepth(ParIterator const & it)
238 Paragraph const & par = *it;
239 LabelType const labeltype = par.layout()->labeltype;
241 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
244 // this will hold the lowest depth encountered up to now.
245 depth_type min_depth = getDepth(it);
246 ParIterator prev_it = it;
249 --prev_it.top().pit();
251 // start of nested inset: go to outer par
253 if (prev_it.empty()) {
254 // start of document: nothing to do
259 // We search for the first paragraph with same label
260 // that is not more deeply nested.
261 Paragraph & prev_par = *prev_it;
262 depth_type const prev_depth = getDepth(prev_it);
263 if (labeltype == prev_par.layout()->labeltype) {
264 if (prev_depth < min_depth)
265 return prev_par.itemdepth + 1;
266 if (prev_depth == min_depth)
267 return prev_par.itemdepth;
269 min_depth = min(min_depth, prev_depth);
270 // small optimization: if we are at depth 0, we won't
271 // find anything else
278 bool needEnumCounterReset(ParIterator const & it)
280 Paragraph const & par = *it;
281 BOOST_ASSERT(par.layout()->labeltype == LABEL_ENUMERATE);
282 depth_type const cur_depth = par.getDepth();
283 ParIterator prev_it = it;
284 while (prev_it.pit()) {
285 --prev_it.top().pit();
286 Paragraph const & prev_par = *prev_it;
287 if (prev_par.getDepth() <= cur_depth)
288 return prev_par.layout()->labeltype != LABEL_ENUMERATE;
290 // start of nested inset: reset
295 // set the label of a paragraph. This includes the counters.
296 void setLabel(Buffer const & buf, ParIterator & it)
298 TextClass const & textclass = buf.params().getTextClass();
299 Paragraph & par = it.paragraph();
300 LayoutPtr const & layout = par.layout();
301 Counters & counters = textclass.counters();
303 if (par.params().startOfAppendix()) {
304 // FIXME: only the counter corresponding to toplevel
305 // sectionning should be reset
307 counters.appendix(true);
309 par.params().appendix(counters.appendix());
311 // Compute the item depth of the paragraph
312 par.itemdepth = getItemDepth(it);
314 if (layout->margintype == MARGIN_MANUAL) {
315 if (par.params().labelWidthString().empty())
316 par.params().labelWidthString(par.translateIfPossible(layout->labelstring(), buf.params()));
318 par.params().labelWidthString(docstring());
321 switch(layout->labeltype) {
323 if (layout->toclevel <= buf.params().secnumdepth
324 && (layout->latextype != LATEX_ENVIRONMENT
325 || isFirstInSequence(it.pit(), it.plist()))) {
326 counters.step(layout->counter);
327 par.params().labelString(
328 par.expandLabel(layout, buf.params()));
330 par.params().labelString(docstring());
333 case LABEL_ITEMIZE: {
334 // At some point of time we should do something more
335 // clever here, like:
336 // par.params().labelString(
337 // buf.params().user_defined_bullet(par.itemdepth).getText());
338 // for now, use a simple hardcoded label
340 switch (par.itemdepth) {
342 itemlabel = char_type(0x2022);
345 itemlabel = char_type(0x2013);
348 itemlabel = char_type(0x2217);
351 itemlabel = char_type(0x2219); // or 0x00b7
354 par.params().labelString(itemlabel);
358 case LABEL_ENUMERATE: {
359 // FIXME: Yes I know this is a really, really! bad solution
361 docstring enumcounter = from_ascii("enum");
363 switch (par.itemdepth) {
375 // not a valid enumdepth...
379 // Maybe we have to reset the enumeration counter.
380 if (needEnumCounterReset(it))
381 counters.reset(enumcounter);
383 counters.step(enumcounter);
387 switch (par.itemdepth) {
389 format = N_("\\arabic{enumi}.");
392 format = N_("(\\alph{enumii})");
395 format = N_("\\roman{enumiii}.");
398 format = N_("\\Alph{enumiv}.");
401 // not a valid enumdepth...
405 par.params().labelString(counters.counterLabel(
406 par.translateIfPossible(from_ascii(format), buf.params())));
411 case LABEL_SENSITIVE: {
412 string const & type = counters.current_float();
413 docstring full_label;
415 full_label = buf.B_("Senseless!!! ");
417 docstring name = buf.B_(textclass.floats().getType(type).name());
418 if (counters.hasCounter(from_utf8(type))) {
419 counters.step(from_utf8(type));
420 full_label = bformat(from_ascii("%1$s %2$s:"),
422 counters.theCounter(from_utf8(type)));
424 full_label = bformat(from_ascii("%1$s #:"), name);
426 par.params().labelString(full_label);
431 par.params().labelString(docstring());
435 case LABEL_TOP_ENVIRONMENT:
436 case LABEL_CENTERED_TOP_ENVIRONMENT:
439 par.params().labelString(
440 par.translateIfPossible(layout->labelstring(),
448 void updateLabels(Buffer const & buf, ParIterator & parit)
450 BOOST_ASSERT(parit.pit() == 0);
452 // set the position of the text in the buffer to be able
453 // to resolve macros in it. This has nothing to do with
454 // labels, but by putting it here we avoid implementing
455 // a whole bunch of traversal routines just for this call.
456 parit.text()->setMacrocontextPosition(parit);
458 depth_type maxdepth = 0;
459 pit_type const lastpit = parit.lastpit();
460 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
461 // reduce depth if necessary
462 parit->params().depth(min(parit->params().depth(), maxdepth));
463 maxdepth = parit->getMaxDepthAfter();
465 // set the counter for this paragraph
466 setLabel(buf, parit);
469 InsetList::const_iterator iit = parit->insetList().begin();
470 InsetList::const_iterator end = parit->insetList().end();
471 for (; iit != end; ++iit) {
472 parit.pos() = iit->pos;
473 iit->inset->updateLabels(buf, parit);
480 // FIXME: buf should should be const because updateLabels() modifies
481 // the contents of the paragraphs.
482 void updateLabels(Buffer const & buf, bool childonly)
484 Buffer const * const master = buf.masterBuffer();
485 // Use the master text class also for child documents
486 TextClass const & textclass = master->params().getTextClass();
489 // If this is a child document start with the master
490 if (master != &buf) {
491 updateLabels(*master);
495 // start over the counters
496 textclass.counters().reset();
499 Buffer & cbuf = const_cast<Buffer &>(buf);
501 if (buf.text().empty()) {
502 // FIXME: we don't call continue with updateLabels()
503 // here because it crashes on newly created documents.
504 // But the TocBackend needs to be initialised
505 // nonetheless so we update the tocBackend manually.
506 cbuf.tocBackend().update();
511 ParIterator parit = par_iterator_begin(buf.inset());
512 updateLabels(buf, parit);
514 cbuf.tocBackend().update();
516 cbuf.structureChanged();