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"
28 #include "LayoutPtr.h"
30 #include "TextClass.h"
31 #include "Paragraph.h"
32 #include "paragraph_funcs.h"
33 #include "ParagraphList.h"
34 #include "ParagraphParameters.h"
35 #include "ParIterator.h"
38 #include "TocBackend.h"
40 #include "frontends/alert.h"
42 #include "insets/InsetBibitem.h"
43 #include "insets/InsetInclude.h"
45 #include "support/convert.h"
46 #include "support/debug.h"
47 #include "support/filetools.h"
48 #include "support/gettext.h"
49 #include "support/lstrings.h"
50 #include "support/textutils.h"
53 using namespace lyx::support;
57 namespace Alert = frontend::Alert;
60 Buffer * checkAndLoadLyXFile(FileName const & filename)
63 Buffer * checkBuffer = theBufferList().getBuffer(filename.absFilename());
65 if (checkBuffer->isClean())
67 docstring const file = makeDisplayPath(filename.absFilename(), 20);
68 docstring text = bformat(_(
69 "The document %1$s is already loaded and has unsaved changes.\n"
70 "Do you want to abandon your changes and reload the version on disk?"), file);
71 if (Alert::prompt(_("Reload saved document?"),
72 text, 0, 1, _("&Reload"), _("&Keep Changes")))
75 // FIXME: should be LFUN_REVERT
76 theBufferList().release(checkBuffer);
78 return checkAndLoadLyXFile(filename);
81 if (filename.exists()) {
82 if (!filename.isReadableFile()) {
83 docstring text = bformat(_("The file %1$s exists but is not "
84 "readable by the current user."),
85 from_utf8(filename.absFilename()));
86 Alert::error(_("File not readable!"), text);
89 Buffer * b = theBufferList().newBuffer(filename.absFilename());
91 // Buffer creation is not possible.
93 if (!b->loadLyXFile(filename)) {
94 theBufferList().release(b);
100 docstring text = bformat(_("The document %1$s does not yet "
101 "exist.\n\nDo you want to create a new document?"),
102 from_utf8(filename.absFilename()));
103 if (!Alert::prompt(_("Create new document?"),
104 text, 0, 1, _("&Create"), _("Cancel")))
105 return newFile(filename.absFilename(), string(), true);
111 // FIXME newFile() should probably be a member method of Application...
112 Buffer * newFile(string const & filename, string const & templatename,
116 Buffer * b = theBufferList().newBuffer(filename);
118 // Buffer creation is not possible.
122 // use defaults.lyx as a default template if it exists.
123 if (templatename.empty())
124 tname = libFileSearch("templates", "defaults.lyx");
126 tname = makeAbsPath(templatename);
128 if (!tname.empty()) {
129 if (!b->readFile(tname)) {
130 docstring const file = makeDisplayPath(tname.absFilename(), 50);
131 docstring const text = bformat(
132 _("The specified document template\n%1$s\ncould not be read."),
134 Alert::error(_("Could not read template"), text);
135 theBufferList().release(b);
142 b->setFileName(filename);
145 b->setReadonly(false);
146 b->setFullyLoaded(true);
152 Buffer * newUnnamedFile(string const & templatename, FileName const & path)
154 static int newfile_number;
156 string document_path = path.absFilename();
157 string filename = addName(document_path,
158 "newfile" + convert<string>(++newfile_number) + ".lyx");
159 while (theBufferList().exists(filename)
160 || FileName(filename).isReadableFile()) {
162 filename = addName(document_path,
163 "newfile" + convert<string>(newfile_number) + ".lyx");
165 return newFile(filename, templatename, false);
169 int countWords(DocIterator const & from, DocIterator const & to)
173 for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
174 // Copied and adapted from isLetter() in ControlSpellChecker
176 && dit.pos() != dit.lastpos()
177 && dit.paragraph().isLetter(dit.pos())
178 && !dit.paragraph().isDeleted(dit.pos())) {
191 int countChars(DocIterator const & from, DocIterator const & to, bool with_blanks)
195 for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
197 if (!dit.inTexted()) continue;
198 Paragraph const & par = dit.paragraph();
199 pos_type const pos = dit.pos();
201 if (pos != dit.lastpos() && !par.isDeleted(pos)) {
202 if (Inset const * ins = par.getInset(pos)) {
205 else if (with_blanks && ins->isSpace())
208 char_type const c = par.getChar(pos);
209 if (isPrintableNonspace(c))
211 else if (isSpace(c) && with_blanks)
217 return chars + blanks;
223 depth_type getDepth(DocIterator const & it)
225 depth_type depth = 0;
226 for (size_t i = 0 ; i < it.depth() ; ++i)
227 if (!it[i].inset().inMathed())
228 depth += it[i].paragraph().getDepth() + 1;
229 // remove 1 since the outer inset does not count
233 depth_type getItemDepth(ParIterator const & it)
235 Paragraph const & par = *it;
236 LabelType const labeltype = par.layout()->labeltype;
238 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
241 // this will hold the lowest depth encountered up to now.
242 depth_type min_depth = getDepth(it);
243 ParIterator prev_it = it;
246 --prev_it.top().pit();
248 // start of nested inset: go to outer par
250 if (prev_it.empty()) {
251 // start of document: nothing to do
256 // We search for the first paragraph with same label
257 // that is not more deeply nested.
258 Paragraph & prev_par = *prev_it;
259 depth_type const prev_depth = getDepth(prev_it);
260 if (labeltype == prev_par.layout()->labeltype) {
261 if (prev_depth < min_depth)
262 return prev_par.itemdepth + 1;
263 if (prev_depth == min_depth)
264 return prev_par.itemdepth;
266 min_depth = min(min_depth, prev_depth);
267 // small optimization: if we are at depth 0, we won't
268 // find anything else
275 bool needEnumCounterReset(ParIterator const & it)
277 Paragraph const & par = *it;
278 BOOST_ASSERT(par.layout()->labeltype == LABEL_ENUMERATE);
279 depth_type const cur_depth = par.getDepth();
280 ParIterator prev_it = it;
281 while (prev_it.pit()) {
282 --prev_it.top().pit();
283 Paragraph const & prev_par = *prev_it;
284 if (prev_par.getDepth() <= cur_depth)
285 return prev_par.layout()->labeltype != LABEL_ENUMERATE;
287 // start of nested inset: reset
292 // set the label of a paragraph. This includes the counters.
293 void setLabel(Buffer const & buf, ParIterator & it)
295 DocumentClass const & textclass = buf.params().documentClass();
296 Paragraph & par = it.paragraph();
297 LayoutPtr const & layout = par.layout();
298 Counters & counters = textclass.counters();
300 if (par.params().startOfAppendix()) {
301 // FIXME: only the counter corresponding to toplevel
302 // sectionning should be reset
304 counters.appendix(true);
306 par.params().appendix(counters.appendix());
308 // Compute the item depth of the paragraph
309 par.itemdepth = getItemDepth(it);
311 if (layout->margintype == MARGIN_MANUAL) {
312 if (par.params().labelWidthString().empty())
313 par.params().labelWidthString(par.translateIfPossible(layout->labelstring(), buf.params()));
315 par.params().labelWidthString(docstring());
318 switch(layout->labeltype) {
320 if (layout->toclevel <= buf.params().secnumdepth
321 && (layout->latextype != LATEX_ENVIRONMENT
322 || isFirstInSequence(it.pit(), it.plist()))) {
323 counters.step(layout->counter);
324 par.params().labelString(
325 par.expandLabel(layout, buf.params()));
327 par.params().labelString(docstring());
330 case LABEL_ITEMIZE: {
331 // At some point of time we should do something more
332 // clever here, like:
333 // par.params().labelString(
334 // buf.params().user_defined_bullet(par.itemdepth).getText());
335 // for now, use a simple hardcoded label
337 switch (par.itemdepth) {
339 itemlabel = char_type(0x2022);
342 itemlabel = char_type(0x2013);
345 itemlabel = char_type(0x2217);
348 itemlabel = char_type(0x2219); // or 0x00b7
351 par.params().labelString(itemlabel);
355 case LABEL_ENUMERATE: {
356 // FIXME: Yes I know this is a really, really! bad solution
358 docstring enumcounter = from_ascii("enum");
360 switch (par.itemdepth) {
372 // not a valid enumdepth...
376 // Maybe we have to reset the enumeration counter.
377 if (needEnumCounterReset(it))
378 counters.reset(enumcounter);
380 counters.step(enumcounter);
384 switch (par.itemdepth) {
386 format = N_("\\arabic{enumi}.");
389 format = N_("(\\alph{enumii})");
392 format = N_("\\roman{enumiii}.");
395 format = N_("\\Alph{enumiv}.");
398 // not a valid enumdepth...
402 par.params().labelString(counters.counterLabel(
403 par.translateIfPossible(from_ascii(format), buf.params())));
408 case LABEL_SENSITIVE: {
409 string const & type = counters.current_float();
410 docstring full_label;
412 full_label = buf.B_("Senseless!!! ");
414 docstring name = buf.B_(textclass.floats().getType(type).name());
415 if (counters.hasCounter(from_utf8(type))) {
416 counters.step(from_utf8(type));
417 full_label = bformat(from_ascii("%1$s %2$s:"),
419 counters.theCounter(from_utf8(type)));
421 full_label = bformat(from_ascii("%1$s #:"), name);
423 par.params().labelString(full_label);
428 par.params().labelString(docstring());
432 case LABEL_TOP_ENVIRONMENT:
433 case LABEL_CENTERED_TOP_ENVIRONMENT:
436 par.params().labelString(
437 par.translateIfPossible(layout->labelstring(),
445 void updateLabels(Buffer const & buf, ParIterator & parit)
447 BOOST_ASSERT(parit.pit() == 0);
449 // set the position of the text in the buffer to be able
450 // to resolve macros in it. This has nothing to do with
451 // labels, but by putting it here we avoid implementing
452 // a whole bunch of traversal routines just for this call.
453 parit.text()->setMacrocontextPosition(parit);
455 depth_type maxdepth = 0;
456 pit_type const lastpit = parit.lastpit();
457 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
458 // reduce depth if necessary
459 parit->params().depth(min(parit->params().depth(), maxdepth));
460 maxdepth = parit->getMaxDepthAfter();
462 // set the counter for this paragraph
463 setLabel(buf, parit);
466 InsetList::const_iterator iit = parit->insetList().begin();
467 InsetList::const_iterator end = parit->insetList().end();
468 for (; iit != end; ++iit) {
469 parit.pos() = iit->pos;
470 iit->inset->updateLabels(parit);
476 // FIXME: buf should should be const because updateLabels() modifies
477 // the contents of the paragraphs.
478 void updateLabels(Buffer const & buf, bool childonly)
480 Buffer const * const master = buf.masterBuffer();
481 // Use the master text class also for child documents
482 DocumentClass const & textclass = master->params().documentClass();
485 // If this is a child document start with the master
486 if (master != &buf) {
487 updateLabels(*master);
491 // start over the counters
492 textclass.counters().reset();
493 buf.clearReferenceCache();
494 buf.loadChildDocuments();
497 Buffer & cbuf = const_cast<Buffer &>(buf);
499 if (buf.text().empty()) {
500 // FIXME: we don't call continue with updateLabels()
501 // here because it crashes on newly created documents.
502 // But the TocBackend needs to be initialised
503 // nonetheless so we update the tocBackend manually.
504 cbuf.tocBackend().update();
509 ParIterator parit = par_iterator_begin(buf.inset());
510 updateLabels(buf, parit);
512 cbuf.tocBackend().update();
514 cbuf.structureChanged();