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 Stefan Schimanski
9 * Full author contact details are available in file CREDITS.
17 #include "LayoutFile.h"
18 #include "BiblioInfo.h"
19 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
25 #include "Converter.h"
27 #include "DocIterator.h"
29 #include "ErrorList.h"
32 #include "FuncRequest.h"
33 #include "InsetIterator.h"
34 #include "InsetList.h"
36 #include "LaTeXFeatures.h"
40 #include "LyXAction.h"
44 #include "output_docbook.h"
46 #include "output_latex.h"
47 #include "output_plaintext.h"
48 #include "paragraph_funcs.h"
49 #include "Paragraph.h"
50 #include "ParagraphParameters.h"
51 #include "ParIterator.h"
52 #include "PDFOptions.h"
53 #include "SpellChecker.h"
56 #include "TexStream.h"
58 #include "TextClass.h"
59 #include "TocBackend.h"
61 #include "VCBackend.h"
63 #include "WordLangTuple.h"
66 #include "insets/InsetBibitem.h"
67 #include "insets/InsetBibtex.h"
68 #include "insets/InsetInclude.h"
69 #include "insets/InsetText.h"
71 #include "mathed/MacroTable.h"
72 #include "mathed/MathMacroTemplate.h"
73 #include "mathed/MathSupport.h"
75 #include "frontends/alert.h"
76 #include "frontends/Delegates.h"
77 #include "frontends/WorkAreaManager.h"
79 #include "graphics/Previews.h"
81 #include "support/lassert.h"
82 #include "support/convert.h"
83 #include "support/debug.h"
84 #include "support/docstring_list.h"
85 #include "support/ExceptionMessage.h"
86 #include "support/FileName.h"
87 #include "support/FileNameList.h"
88 #include "support/filetools.h"
89 #include "support/ForkedCalls.h"
90 #include "support/gettext.h"
91 #include "support/gzstream.h"
92 #include "support/lstrings.h"
93 #include "support/lyxalgo.h"
94 #include "support/os.h"
95 #include "support/Package.h"
96 #include "support/Path.h"
97 #include "support/textutils.h"
98 #include "support/types.h"
100 #include <boost/bind.hpp>
101 #include <boost/shared_ptr.hpp>
113 using namespace lyx::support;
117 namespace Alert = frontend::Alert;
118 namespace os = support::os;
122 // Do not remove the comment below, so we get merge conflict in
123 // independent branches. Instead add your own.
124 int const LYX_FORMAT = 349; // jspitzm: initial XeTeX support
126 typedef map<string, bool> DepClean;
127 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
131 class BufferSet : public std::set<Buffer const *> {};
136 Impl(Buffer & parent, FileName const & file, bool readonly);
150 mutable TexRow texrow;
152 /// need to regenerate .tex?
156 mutable bool lyx_clean;
158 /// is autosave needed?
159 mutable bool bak_clean;
161 /// is this a unnamed file (New...)?
167 /// name of the file the buffer is associated with.
170 /** Set to true only when the file is fully loaded.
171 * Used to prevent the premature generation of previews
172 * and by the citation inset.
174 bool file_fully_loaded;
177 mutable TocBackend toc_backend;
180 typedef pair<DocIterator, MacroData> ScopeMacro;
181 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
182 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
183 /// map from the macro name to the position map,
184 /// which maps the macro definition position to the scope and the MacroData.
185 NamePositionScopeMacroMap macros;
188 /// positions of child buffers in the buffer
189 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
190 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
191 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
192 /// position of children buffers in this buffer
193 BufferPositionMap children_positions;
194 /// map from children inclusion positions to their scope and their buffer
195 PositionScopeBufferMap position_to_children;
197 /// Container for all sort of Buffer dependant errors.
198 map<string, ErrorList> errorLists;
200 /// timestamp and checksum used to test if the file has been externally
201 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
203 unsigned long checksum_;
206 frontend::WorkAreaManager * wa_;
211 /// A cache for the bibfiles (including bibfiles of loaded child
212 /// documents), needed for appropriate update of natbib labels.
213 mutable support::FileNameList bibfilesCache_;
215 // FIXME The caching mechanism could be improved. At present, we have a
216 // cache for each Buffer, that caches all the bibliography info for that
217 // Buffer. A more efficient solution would be to have a global cache per
218 // file, and then to construct the Buffer's bibinfo from that.
219 /// A cache for bibliography info
220 mutable BiblioInfo bibinfo_;
221 /// whether the bibinfo cache is valid
222 bool bibinfoCacheValid_;
223 /// Cache of timestamps of .bib files
224 map<FileName, time_t> bibfileStatus_;
226 mutable RefCache ref_cache_;
228 /// our Text that should be wrapped in an InsetText
231 /// This is here to force the test to be done whenever parent_buffer
233 Buffer const * parent() const {
234 // if parent_buffer is not loaded, then it has been unloaded,
235 // which means that parent_buffer is an invalid pointer. So we
236 // set it to null in that case.
237 if (!theBufferList().isLoaded(parent_buffer))
239 return parent_buffer;
242 void setParent(Buffer const * pb) { parent_buffer = pb; }
244 /// So we can force access via the accessors.
245 mutable Buffer const * parent_buffer;
249 /// Creates the per buffer temporary directory
250 static FileName createBufferTmpDir()
253 // We are in our own directory. Why bother to mangle name?
254 // In fact I wrote this code to circumvent a problematic behaviour
255 // (bug?) of EMX mkstemp().
256 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
257 convert<string>(count++));
259 if (!tmpfl.createDirectory(0777)) {
260 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
261 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
262 from_utf8(tmpfl.absFilename())));
268 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
269 : lyx_clean(true), bak_clean(true), unnamed(false),
270 read_only(readonly_), filename(file), file_fully_loaded(false),
271 toc_backend(&parent), macro_lock(false), timestamp_(0),
272 checksum_(0), wa_(0), undo_(parent), bibinfoCacheValid_(false),
275 temppath = createBufferTmpDir();
276 lyxvc.setBuffer(&parent);
278 wa_ = new frontend::WorkAreaManager;
282 Buffer::Buffer(string const & file, bool readonly)
283 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
285 LYXERR(Debug::INFO, "Buffer::Buffer()");
287 d->inset = new InsetText(*this);
288 d->inset->setAutoBreakRows(true);
289 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
295 LYXERR(Debug::INFO, "Buffer::~Buffer()");
296 // here the buffer should take care that it is
297 // saved properly, before it goes into the void.
299 // GuiView already destroyed
302 if (d->unnamed && d->filename.extension() == "internal") {
303 // No need to do additional cleanups for internal buffer.
308 // loop over children
309 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
310 Impl::BufferPositionMap::iterator end = d->children_positions.end();
311 for (; it != end; ++it) {
312 Buffer * child = const_cast<Buffer *>(it->first);
313 // The child buffer might have been closed already.
314 if (theBufferList().isLoaded(child))
315 theBufferList().releaseChild(this, child);
318 // clear references to children in macro tables
319 d->children_positions.clear();
320 d->position_to_children.clear();
322 if (!d->temppath.destroyDirectory()) {
323 Alert::warning(_("Could not remove temporary directory"),
324 bformat(_("Could not remove the temporary directory %1$s"),
325 from_utf8(d->temppath.absFilename())));
328 // Remove any previewed LaTeX snippets associated with this buffer.
329 thePreviews().removeLoader(*this);
335 void Buffer::changed() const
342 frontend::WorkAreaManager & Buffer::workAreaManager() const
344 LASSERT(d->wa_, /**/);
349 Text & Buffer::text() const
351 return d->inset->text();
355 Inset & Buffer::inset() const
361 BufferParams & Buffer::params()
367 BufferParams const & Buffer::params() const
373 ParagraphList & Buffer::paragraphs()
375 return text().paragraphs();
379 ParagraphList const & Buffer::paragraphs() const
381 return text().paragraphs();
385 LyXVC & Buffer::lyxvc()
391 LyXVC const & Buffer::lyxvc() const
397 string const Buffer::temppath() const
399 return d->temppath.absFilename();
403 TexRow & Buffer::texrow()
409 TexRow const & Buffer::texrow() const
415 TocBackend & Buffer::tocBackend() const
417 return d->toc_backend;
421 Undo & Buffer::undo()
427 string Buffer::latexName(bool const no_path) const
429 FileName latex_name = makeLatexName(d->filename);
430 return no_path ? latex_name.onlyFileName()
431 : latex_name.absFilename();
435 string Buffer::logName(LogType * type) const
437 string const filename = latexName(false);
439 if (filename.empty()) {
445 string const path = temppath();
447 FileName const fname(addName(temppath(),
448 onlyFilename(changeExtension(filename,
450 FileName const bname(
451 addName(path, onlyFilename(
452 changeExtension(filename,
453 formats.extension("literate") + ".out"))));
455 // If no Latex log or Build log is newer, show Build log
457 if (bname.exists() &&
458 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
459 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
462 return bname.absFilename();
464 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
467 return fname.absFilename();
471 void Buffer::setReadonly(bool const flag)
473 if (d->read_only != flag) {
480 void Buffer::setFileName(string const & newfile)
482 d->filename = makeAbsPath(newfile);
483 setReadonly(d->filename.isReadOnly());
488 int Buffer::readHeader(Lexer & lex)
490 int unknown_tokens = 0;
492 int begin_header_line = -1;
494 // Initialize parameters that may be/go lacking in header:
495 params().branchlist().clear();
496 params().preamble.erase();
497 params().options.erase();
498 params().master.erase();
499 params().float_placement.erase();
500 params().paperwidth.erase();
501 params().paperheight.erase();
502 params().leftmargin.erase();
503 params().rightmargin.erase();
504 params().topmargin.erase();
505 params().bottommargin.erase();
506 params().headheight.erase();
507 params().headsep.erase();
508 params().footskip.erase();
509 params().columnsep.erase();
510 params().fontsCJK.erase();
511 params().listings_params.clear();
512 params().clearLayoutModules();
513 params().clearRemovedModules();
514 params().pdfoptions().clear();
516 for (int i = 0; i < 4; ++i) {
517 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
518 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
521 ErrorList & errorList = d->errorLists["Parse"];
530 if (token == "\\end_header")
534 if (token == "\\begin_header") {
535 begin_header_line = line;
539 LYXERR(Debug::PARSER, "Handling document header token: `"
542 string unknown = params().readToken(lex, token, d->filename.onlyPath());
543 if (!unknown.empty()) {
544 if (unknown[0] != '\\' && token == "\\textclass") {
545 Alert::warning(_("Unknown document class"),
546 bformat(_("Using the default document class, because the "
547 "class %1$s is unknown."), from_utf8(unknown)));
550 docstring const s = bformat(_("Unknown token: "
554 errorList.push_back(ErrorItem(_("Document header error"),
559 if (begin_header_line) {
560 docstring const s = _("\\begin_header is missing");
561 errorList.push_back(ErrorItem(_("Document header error"),
565 params().makeDocumentClass();
567 return unknown_tokens;
572 // changed to be public and have one parameter
573 // Returns true if "\end_document" is not read (Asger)
574 bool Buffer::readDocument(Lexer & lex)
576 ErrorList & errorList = d->errorLists["Parse"];
579 if (!lex.checkFor("\\begin_document")) {
580 docstring const s = _("\\begin_document is missing");
581 errorList.push_back(ErrorItem(_("Document header error"),
585 // we are reading in a brand new document
586 LASSERT(paragraphs().empty(), /**/);
590 if (params().outputChanges) {
591 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
592 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
593 LaTeXFeatures::isAvailable("xcolor");
595 if (!dvipost && !xcolorulem) {
596 Alert::warning(_("Changes not shown in LaTeX output"),
597 _("Changes will not be highlighted in LaTeX output, "
598 "because neither dvipost nor xcolor/ulem are installed.\n"
599 "Please install these packages or redefine "
600 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
601 } else if (!xcolorulem) {
602 Alert::warning(_("Changes not shown in LaTeX output"),
603 _("Changes will not be highlighted in LaTeX output "
604 "when using pdflatex, because xcolor and ulem are not installed.\n"
605 "Please install both packages or redefine "
606 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
610 if (!params().master.empty()) {
611 FileName const master_file = makeAbsPath(params().master,
612 onlyPath(absFileName()));
613 if (isLyXFilename(master_file.absFilename())) {
615 checkAndLoadLyXFile(master_file, true);
617 // necessary e.g. after a reload
618 // to re-register the child (bug 5873)
619 // FIXME: clean up updateMacros (here, only
620 // child registering is needed).
621 master->updateMacros();
622 // set master as master buffer, but only
623 // if we are a real child
624 if (master->isChild(this))
626 // if the master is not fully loaded
627 // it is probably just loading this
628 // child. No warning needed then.
629 else if (master->isFullyLoaded())
630 LYXERR0("The master '"
632 << "' assigned to this document ("
634 << ") does not include "
635 "this document. Ignoring the master assignment.");
641 bool const res = text().read(*this, lex, errorList, d->inset);
644 updateMacroInstances();
649 // needed to insert the selection
650 void Buffer::insertStringAsLines(ParagraphList & pars,
651 pit_type & pit, pos_type & pos,
652 Font const & fn, docstring const & str, bool autobreakrows)
656 // insert the string, don't insert doublespace
657 bool space_inserted = true;
658 for (docstring::const_iterator cit = str.begin();
659 cit != str.end(); ++cit) {
660 Paragraph & par = pars[pit];
662 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
663 breakParagraph(params(), pars, pit, pos,
664 par.layout().isEnvironment());
667 space_inserted = true;
671 // do not insert consecutive spaces if !free_spacing
672 } else if ((*cit == ' ' || *cit == '\t') &&
673 space_inserted && !par.isFreeSpacing()) {
675 } else if (*cit == '\t') {
676 if (!par.isFreeSpacing()) {
677 // tabs are like spaces here
678 par.insertChar(pos, ' ', font, params().trackChanges);
680 space_inserted = true;
682 par.insertChar(pos, *cit, font, params().trackChanges);
684 space_inserted = true;
686 } else if (!isPrintable(*cit)) {
687 // Ignore unprintables
690 // just insert the character
691 par.insertChar(pos, *cit, font, params().trackChanges);
693 space_inserted = (*cit == ' ');
700 bool Buffer::readString(string const & s)
702 params().compressed = false;
704 // remove dummy empty par
705 paragraphs().clear();
709 FileName const name = FileName::tempName("Buffer_readString");
710 switch (readFile(lex, name, true)) {
714 // We need to call lyx2lyx, so write the input to a file
715 ofstream os(name.toFilesystemEncoding().c_str());
718 return readFile(name);
728 bool Buffer::readFile(FileName const & filename)
730 FileName fname(filename);
732 params().compressed = fname.isZippedFile();
734 // remove dummy empty par
735 paragraphs().clear();
738 if (readFile(lex, fname) != success)
745 bool Buffer::isFullyLoaded() const
747 return d->file_fully_loaded;
751 void Buffer::setFullyLoaded(bool value)
753 d->file_fully_loaded = value;
757 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
760 LASSERT(!filename.empty(), /**/);
762 // the first (non-comment) token _must_ be...
763 if (!lex.checkFor("\\lyxformat")) {
764 Alert::error(_("Document format failure"),
765 bformat(_("%1$s is not a readable LyX document."),
766 from_utf8(filename.absFilename())));
772 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
773 // if present remove ".," from string.
774 size_t dot = tmp_format.find_first_of(".,");
775 //lyxerr << " dot found at " << dot << endl;
776 if (dot != string::npos)
777 tmp_format.erase(dot, 1);
778 int const file_format = convert<int>(tmp_format);
779 //lyxerr << "format: " << file_format << endl;
781 // save timestamp and checksum of the original disk file, making sure
782 // to not overwrite them with those of the file created in the tempdir
783 // when it has to be converted to the current format.
785 // Save the timestamp and checksum of disk file. If filename is an
786 // emergency file, save the timestamp and checksum of the original lyx file
787 // because isExternallyModified will check for this file. (BUG4193)
788 string diskfile = filename.absFilename();
789 if (suffixIs(diskfile, ".emergency"))
790 diskfile = diskfile.substr(0, diskfile.size() - 10);
791 saveCheckSum(FileName(diskfile));
794 if (file_format != LYX_FORMAT) {
797 // lyx2lyx would fail
800 FileName const tmpfile = FileName::tempName("Buffer_readFile");
801 if (tmpfile.empty()) {
802 Alert::error(_("Conversion failed"),
803 bformat(_("%1$s is from a different"
804 " version of LyX, but a temporary"
805 " file for converting it could"
807 from_utf8(filename.absFilename())));
810 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
811 if (lyx2lyx.empty()) {
812 Alert::error(_("Conversion script not found"),
813 bformat(_("%1$s is from a different"
814 " version of LyX, but the"
815 " conversion script lyx2lyx"
816 " could not be found."),
817 from_utf8(filename.absFilename())));
820 ostringstream command;
821 command << os::python()
822 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
823 << " -t " << convert<string>(LYX_FORMAT)
824 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
825 << ' ' << quoteName(filename.toFilesystemEncoding());
826 string const command_str = command.str();
828 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
830 cmd_ret const ret = runCommand(command_str);
831 if (ret.first != 0) {
832 Alert::error(_("Conversion script failed"),
833 bformat(_("%1$s is from a different version"
834 " of LyX, but the lyx2lyx script"
835 " failed to convert it."),
836 from_utf8(filename.absFilename())));
839 bool const ret = readFile(tmpfile);
840 // Do stuff with tmpfile name and buffer name here.
841 return ret ? success : failure;
846 if (readDocument(lex)) {
847 Alert::error(_("Document format failure"),
848 bformat(_("%1$s ended unexpectedly, which means"
849 " that it is probably corrupted."),
850 from_utf8(filename.absFilename())));
853 d->file_fully_loaded = true;
858 // Should probably be moved to somewhere else: BufferView? LyXView?
859 bool Buffer::save() const
861 // We don't need autosaves in the immediate future. (Asger)
862 resetAutosaveTimers();
864 string const encodedFilename = d->filename.toFilesystemEncoding();
867 bool madeBackup = false;
869 // make a backup if the file already exists
870 if (lyxrc.make_backup && fileName().exists()) {
871 backupName = FileName(absFileName() + '~');
872 if (!lyxrc.backupdir_path.empty()) {
873 string const mangledName =
874 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
875 backupName = FileName(addName(lyxrc.backupdir_path,
878 if (fileName().copyTo(backupName)) {
881 Alert::error(_("Backup failure"),
882 bformat(_("Cannot create backup file %1$s.\n"
883 "Please check whether the directory exists and is writeable."),
884 from_utf8(backupName.absFilename())));
885 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
889 // ask if the disk file has been externally modified (use checksum method)
890 if (fileName().exists() && isExternallyModified(checksum_method)) {
891 docstring const file = makeDisplayPath(absFileName(), 20);
892 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
893 "you want to overwrite this file?"), file);
894 int const ret = Alert::prompt(_("Overwrite modified file?"),
895 text, 1, 1, _("&Overwrite"), _("&Cancel"));
900 if (writeFile(d->filename)) {
904 // Saving failed, so backup is not backup
906 backupName.moveTo(d->filename);
912 bool Buffer::writeFile(FileName const & fname) const
914 if (d->read_only && fname == d->filename)
919 docstring const str = bformat(_("Saving document %1$s..."),
920 makeDisplayPath(fname.absFilename()));
923 if (params().compressed) {
924 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
925 retval = ofs && write(ofs);
927 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
928 retval = ofs && write(ofs);
932 message(str + _(" could not write file!"));
936 removeAutosaveFile();
938 saveCheckSum(d->filename);
939 message(str + _(" done."));
945 bool Buffer::write(ostream & ofs) const
948 // Use the standard "C" locale for file output.
949 ofs.imbue(locale::classic());
952 // The top of the file should not be written by params().
954 // write out a comment in the top of the file
955 ofs << "#LyX " << lyx_version
956 << " created this file. For more info see http://www.lyx.org/\n"
957 << "\\lyxformat " << LYX_FORMAT << "\n"
958 << "\\begin_document\n";
960 /// For each author, set 'used' to true if there is a change
961 /// by this author in the document; otherwise set it to 'false'.
962 AuthorList::Authors::const_iterator a_it = params().authors().begin();
963 AuthorList::Authors::const_iterator a_end = params().authors().end();
964 for (; a_it != a_end; ++a_it)
965 a_it->second.setUsed(false);
967 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
968 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
969 for ( ; it != end; ++it)
970 it->checkAuthors(params().authors());
972 // now write out the buffer parameters.
973 ofs << "\\begin_header\n";
974 params().writeFile(ofs);
975 ofs << "\\end_header\n";
978 ofs << "\n\\begin_body\n";
979 text().write(*this, ofs);
980 ofs << "\n\\end_body\n";
982 // Write marker that shows file is complete
983 ofs << "\\end_document" << endl;
985 // Shouldn't really be needed....
988 // how to check if close went ok?
989 // Following is an attempt... (BE 20001011)
991 // good() returns false if any error occured, including some
993 // bad() returns true if something bad happened in the buffer,
994 // which should include file system full errors.
999 lyxerr << "File was not closed properly." << endl;
1006 bool Buffer::makeLaTeXFile(FileName const & fname,
1007 string const & original_path,
1008 OutputParams const & runparams_in,
1009 bool output_preamble, bool output_body) const
1011 OutputParams runparams = runparams_in;
1012 if (params().useXetex)
1013 runparams.flavor = OutputParams::XETEX;
1015 string const encoding = runparams.encoding->iconvName();
1016 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1019 try { ofs.reset(encoding); }
1020 catch (iconv_codecvt_facet_exception & e) {
1021 lyxerr << "Caught iconv exception: " << e.what() << endl;
1022 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1023 "verify that the support software for your encoding (%1$s) is "
1024 "properly installed"), from_ascii(encoding)));
1027 if (!openFileWrite(ofs, fname))
1030 //TexStream ts(ofs.rdbuf(), &texrow());
1031 ErrorList & errorList = d->errorLists["Export"];
1033 bool failed_export = false;
1036 writeLaTeXSource(ofs, original_path,
1037 runparams, output_preamble, output_body);
1039 catch (EncodingException & e) {
1040 odocstringstream ods;
1041 ods.put(e.failed_char);
1043 oss << "0x" << hex << e.failed_char << dec;
1044 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1045 " (code point %2$s)"),
1046 ods.str(), from_utf8(oss.str()));
1047 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1048 "representable in the chosen encoding.\n"
1049 "Changing the document encoding to utf8 could help."),
1050 e.par_id, e.pos, e.pos + 1));
1051 failed_export = true;
1053 catch (iconv_codecvt_facet_exception & e) {
1054 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1055 _(e.what()), -1, 0, 0));
1056 failed_export = true;
1058 catch (exception const & e) {
1059 errorList.push_back(ErrorItem(_("conversion failed"),
1060 _(e.what()), -1, 0, 0));
1061 failed_export = true;
1064 lyxerr << "Caught some really weird exception..." << endl;
1070 failed_export = true;
1071 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1075 return !failed_export;
1079 void Buffer::writeLaTeXSource(odocstream & os,
1080 string const & original_path,
1081 OutputParams const & runparams_in,
1082 bool const output_preamble, bool const output_body) const
1084 // The child documents, if any, shall be already loaded at this point.
1086 OutputParams runparams = runparams_in;
1088 // Classify the unicode characters appearing in math insets
1089 Encodings::initUnicodeMath(*this);
1091 // validate the buffer.
1092 LYXERR(Debug::LATEX, " Validating buffer...");
1093 LaTeXFeatures features(*this, params(), runparams);
1095 LYXERR(Debug::LATEX, " Buffer validation done.");
1097 // The starting paragraph of the coming rows is the
1098 // first paragraph of the document. (Asger)
1099 if (output_preamble && runparams.nice) {
1100 os << "%% LyX " << lyx_version << " created this file. "
1101 "For more info, see http://www.lyx.org/.\n"
1102 "%% Do not edit unless you really know what "
1104 d->texrow.newline();
1105 d->texrow.newline();
1107 LYXERR(Debug::INFO, "lyx document header finished");
1109 // Don't move this behind the parent_buffer=0 code below,
1110 // because then the macros will not get the right "redefinition"
1111 // flag as they don't see the parent macros which are output before.
1114 // fold macros if possible, still with parent buffer as the
1115 // macros will be put in the prefix anyway.
1116 updateMacroInstances();
1118 // There are a few differences between nice LaTeX and usual files:
1119 // usual is \batchmode and has a
1120 // special input@path to allow the including of figures
1121 // with either \input or \includegraphics (what figinsets do).
1122 // input@path is set when the actual parameter
1123 // original_path is set. This is done for usual tex-file, but not
1124 // for nice-latex-file. (Matthias 250696)
1125 // Note that input@path is only needed for something the user does
1126 // in the preamble, included .tex files or ERT, files included by
1127 // LyX work without it.
1128 if (output_preamble) {
1129 if (!runparams.nice) {
1130 // code for usual, NOT nice-latex-file
1131 os << "\\batchmode\n"; // changed
1132 // from \nonstopmode
1133 d->texrow.newline();
1135 if (!original_path.empty()) {
1137 // We don't know the encoding of inputpath
1138 docstring const inputpath = from_utf8(latex_path(original_path));
1139 os << "\\makeatletter\n"
1140 << "\\def\\input@path{{"
1141 << inputpath << "/}}\n"
1142 << "\\makeatother\n";
1143 d->texrow.newline();
1144 d->texrow.newline();
1145 d->texrow.newline();
1148 // get parent macros (if this buffer has a parent) which will be
1149 // written at the document begin further down.
1150 MacroSet parentMacros;
1151 listParentMacros(parentMacros, features);
1153 // Write the preamble
1154 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1156 runparams.use_japanese = features.isRequired("japanese");
1162 os << "\\begin{document}\n";
1163 d->texrow.newline();
1165 // output the parent macros
1166 MacroSet::iterator it = parentMacros.begin();
1167 MacroSet::iterator end = parentMacros.end();
1168 for (; it != end; ++it)
1169 (*it)->write(os, true);
1170 } // output_preamble
1172 d->texrow.start(paragraphs().begin()->id(), 0);
1174 LYXERR(Debug::INFO, "preamble finished, now the body.");
1176 // if we are doing a real file with body, even if this is the
1177 // child of some other buffer, let's cut the link here.
1178 // This happens for example if only a child document is printed.
1179 Buffer const * save_parent = 0;
1180 if (output_preamble) {
1181 save_parent = d->parent();
1186 latexParagraphs(*this, text(), os, d->texrow, runparams);
1188 // Restore the parenthood if needed
1189 if (output_preamble)
1190 d->setParent(save_parent);
1192 // add this just in case after all the paragraphs
1194 d->texrow.newline();
1196 if (output_preamble) {
1197 os << "\\end{document}\n";
1198 d->texrow.newline();
1199 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1201 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1203 runparams_in.encoding = runparams.encoding;
1205 // Just to be sure. (Asger)
1206 d->texrow.newline();
1208 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1209 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1213 bool Buffer::isLatex() const
1215 return params().documentClass().outputType() == LATEX;
1219 bool Buffer::isLiterate() const
1221 return params().documentClass().outputType() == LITERATE;
1225 bool Buffer::isDocBook() const
1227 return params().documentClass().outputType() == DOCBOOK;
1231 void Buffer::makeDocBookFile(FileName const & fname,
1232 OutputParams const & runparams,
1233 bool const body_only) const
1235 LYXERR(Debug::LATEX, "makeDocBookFile...");
1238 if (!openFileWrite(ofs, fname))
1241 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1245 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1249 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1250 OutputParams const & runparams,
1251 bool const only_body) const
1253 LaTeXFeatures features(*this, params(), runparams);
1258 DocumentClass const & tclass = params().documentClass();
1259 string const top_element = tclass.latexname();
1262 if (runparams.flavor == OutputParams::XML)
1263 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1266 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1269 if (! tclass.class_header().empty())
1270 os << from_ascii(tclass.class_header());
1271 else if (runparams.flavor == OutputParams::XML)
1272 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1273 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1275 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1277 docstring preamble = from_utf8(params().preamble);
1278 if (runparams.flavor != OutputParams::XML ) {
1279 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1280 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1281 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1282 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1285 string const name = runparams.nice
1286 ? changeExtension(absFileName(), ".sgml") : fname;
1287 preamble += features.getIncludedFiles(name);
1288 preamble += features.getLyXSGMLEntities();
1290 if (!preamble.empty()) {
1291 os << "\n [ " << preamble << " ]";
1296 string top = top_element;
1298 if (runparams.flavor == OutputParams::XML)
1299 top += params().language->code();
1301 top += params().language->code().substr(0, 2);
1304 if (!params().options.empty()) {
1306 top += params().options;
1309 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1310 << " file was created by LyX " << lyx_version
1311 << "\n See http://www.lyx.org/ for more information -->\n";
1313 params().documentClass().counters().reset();
1317 sgml::openTag(os, top);
1319 docbookParagraphs(paragraphs(), *this, os, runparams);
1320 sgml::closeTag(os, top_element);
1324 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1325 // Other flags: -wall -v0 -x
1326 int Buffer::runChktex()
1330 // get LaTeX-Filename
1331 FileName const path(temppath());
1332 string const name = addName(path.absFilename(), latexName());
1333 string const org_path = filePath();
1335 PathChanger p(path); // path to LaTeX file
1336 message(_("Running chktex..."));
1338 // Generate the LaTeX file if neccessary
1339 OutputParams runparams(¶ms().encoding());
1340 runparams.flavor = OutputParams::LATEX;
1341 runparams.nice = false;
1342 makeLaTeXFile(FileName(name), org_path, runparams);
1345 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1346 int const res = chktex.run(terr); // run chktex
1349 Alert::error(_("chktex failure"),
1350 _("Could not run chktex successfully."));
1351 } else if (res > 0) {
1352 ErrorList & errlist = d->errorLists["ChkTeX"];
1354 bufferErrors(terr, errlist);
1365 void Buffer::validate(LaTeXFeatures & features) const
1367 params().validate(features);
1371 for_each(paragraphs().begin(), paragraphs().end(),
1372 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1374 if (lyxerr.debugging(Debug::LATEX)) {
1375 features.showStruct();
1380 void Buffer::getLabelList(vector<docstring> & list) const
1382 // If this is a child document, use the parent's list instead.
1383 Buffer const * const pbuf = d->parent();
1385 pbuf->getLabelList(list);
1390 Toc & toc = d->toc_backend.toc("label");
1391 TocIterator toc_it = toc.begin();
1392 TocIterator end = toc.end();
1393 for (; toc_it != end; ++toc_it) {
1394 if (toc_it->depth() == 0)
1395 list.push_back(toc_it->str());
1400 void Buffer::updateBibfilesCache(UpdateScope scope) const
1402 // If this is a child document, use the parent's cache instead.
1403 Buffer const * const pbuf = d->parent();
1404 if (pbuf && scope != UpdateChildOnly) {
1405 pbuf->updateBibfilesCache();
1409 d->bibfilesCache_.clear();
1410 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1411 if (it->lyxCode() == BIBTEX_CODE) {
1412 InsetBibtex const & inset =
1413 static_cast<InsetBibtex const &>(*it);
1414 support::FileNameList const bibfiles = inset.getBibFiles();
1415 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1418 } else if (it->lyxCode() == INCLUDE_CODE) {
1419 InsetInclude & inset =
1420 static_cast<InsetInclude &>(*it);
1421 inset.updateBibfilesCache();
1422 support::FileNameList const & bibfiles =
1423 inset.getBibfilesCache();
1424 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1429 // the bibinfo cache is now invalid
1430 d->bibinfoCacheValid_ = false;
1434 void Buffer::invalidateBibinfoCache()
1436 d->bibinfoCacheValid_ = false;
1440 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1442 // If this is a child document, use the parent's cache instead.
1443 Buffer const * const pbuf = d->parent();
1444 if (pbuf && scope != UpdateChildOnly)
1445 return pbuf->getBibfilesCache();
1447 // We update the cache when first used instead of at loading time.
1448 if (d->bibfilesCache_.empty())
1449 const_cast<Buffer *>(this)->updateBibfilesCache(scope);
1451 return d->bibfilesCache_;
1455 BiblioInfo const & Buffer::masterBibInfo() const
1457 // if this is a child document and the parent is already loaded
1458 // use the parent's list instead [ale990412]
1459 Buffer const * const tmp = masterBuffer();
1462 return tmp->masterBibInfo();
1463 return localBibInfo();
1467 BiblioInfo const & Buffer::localBibInfo() const
1469 if (d->bibinfoCacheValid_) {
1470 support::FileNameList const & bibfilesCache = getBibfilesCache();
1471 // compare the cached timestamps with the actual ones.
1472 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1473 support::FileNameList::const_iterator en = bibfilesCache.end();
1474 for (; ei != en; ++ ei) {
1475 time_t lastw = ei->lastModified();
1476 if (lastw != d->bibfileStatus_[*ei]) {
1477 d->bibinfoCacheValid_ = false;
1478 d->bibfileStatus_[*ei] = lastw;
1484 if (!d->bibinfoCacheValid_) {
1485 d->bibinfo_.clear();
1486 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1487 it->fillWithBibKeys(d->bibinfo_, it);
1488 d->bibinfoCacheValid_ = true;
1494 bool Buffer::isDepClean(string const & name) const
1496 DepClean::const_iterator const it = d->dep_clean.find(name);
1497 if (it == d->dep_clean.end())
1503 void Buffer::markDepClean(string const & name)
1505 d->dep_clean[name] = true;
1509 bool Buffer::dispatch(string const & command, bool * result)
1511 return dispatch(lyxaction.lookupFunc(command), result);
1515 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1517 bool dispatched = true;
1519 switch (func.action) {
1520 case LFUN_BUFFER_EXPORT: {
1521 bool const tmp = doExport(to_utf8(func.argument()), false);
1527 case LFUN_BRANCH_ACTIVATE:
1528 case LFUN_BRANCH_DEACTIVATE: {
1529 BranchList & branchList = params().branchlist();
1530 docstring const branchName = func.argument();
1531 // the case without a branch name is handled elsewhere
1532 if (branchName.empty()) {
1536 Branch * branch = branchList.find(branchName);
1538 LYXERR0("Branch " << branchName << " does not exist.");
1540 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1552 void Buffer::changeLanguage(Language const * from, Language const * to)
1554 LASSERT(from, /**/);
1557 for_each(par_iterator_begin(),
1559 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1563 bool Buffer::isMultiLingual() const
1565 ParConstIterator end = par_iterator_end();
1566 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1567 if (it->isMultiLingual(params()))
1574 DocIterator Buffer::getParFromID(int const id) const
1576 Buffer * buf = const_cast<Buffer *>(this);
1578 // John says this is called with id == -1 from undo
1579 lyxerr << "getParFromID(), id: " << id << endl;
1580 return doc_iterator_end(buf);
1583 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
1584 if (it.paragraph().id() == id)
1587 return doc_iterator_end(buf);
1591 bool Buffer::hasParWithID(int const id) const
1593 return !getParFromID(id).atEnd();
1597 ParIterator Buffer::par_iterator_begin()
1599 return ParIterator(doc_iterator_begin(this));
1603 ParIterator Buffer::par_iterator_end()
1605 return ParIterator(doc_iterator_end(this));
1609 ParConstIterator Buffer::par_iterator_begin() const
1611 return ParConstIterator(doc_iterator_begin(this));
1615 ParConstIterator Buffer::par_iterator_end() const
1617 return ParConstIterator(doc_iterator_end(this));
1621 Language const * Buffer::language() const
1623 return params().language;
1627 docstring const Buffer::B_(string const & l10n) const
1629 return params().B_(l10n);
1633 bool Buffer::isClean() const
1635 return d->lyx_clean;
1639 bool Buffer::isBakClean() const
1641 return d->bak_clean;
1645 bool Buffer::isExternallyModified(CheckMethod method) const
1647 LASSERT(d->filename.exists(), /**/);
1648 // if method == timestamp, check timestamp before checksum
1649 return (method == checksum_method
1650 || d->timestamp_ != d->filename.lastModified())
1651 && d->checksum_ != d->filename.checksum();
1655 void Buffer::saveCheckSum(FileName const & file) const
1657 if (file.exists()) {
1658 d->timestamp_ = file.lastModified();
1659 d->checksum_ = file.checksum();
1661 // in the case of save to a new file.
1668 void Buffer::markClean() const
1670 if (!d->lyx_clean) {
1671 d->lyx_clean = true;
1674 // if the .lyx file has been saved, we don't need an
1676 d->bak_clean = true;
1680 void Buffer::markBakClean() const
1682 d->bak_clean = true;
1686 void Buffer::setUnnamed(bool flag)
1692 bool Buffer::isUnnamed() const
1698 // FIXME: this function should be moved to buffer_pimpl.C
1699 void Buffer::markDirty()
1702 d->lyx_clean = false;
1705 d->bak_clean = false;
1707 DepClean::iterator it = d->dep_clean.begin();
1708 DepClean::const_iterator const end = d->dep_clean.end();
1710 for (; it != end; ++it)
1715 FileName Buffer::fileName() const
1721 string Buffer::absFileName() const
1723 return d->filename.absFilename();
1727 string Buffer::filePath() const
1729 return d->filename.onlyPath().absFilename() + "/";
1733 bool Buffer::isReadonly() const
1735 return d->read_only;
1739 void Buffer::setParent(Buffer const * buffer)
1741 // Avoids recursive include.
1742 d->setParent(buffer == this ? 0 : buffer);
1747 Buffer const * Buffer::parent() const
1753 void Buffer::collectRelatives(BufferSet & bufs) const
1757 parent()->collectRelatives(bufs);
1759 // loop over children
1760 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1761 Impl::BufferPositionMap::iterator end = d->children_positions.end();
1762 for (; it != end; ++it)
1763 bufs.insert(const_cast<Buffer *>(it->first));
1767 std::vector<Buffer const *> Buffer::allRelatives() const
1770 collectRelatives(bufs);
1771 BufferSet::iterator it = bufs.begin();
1772 std::vector<Buffer const *> ret;
1773 for (; it != bufs.end(); ++it)
1779 Buffer const * Buffer::masterBuffer() const
1781 Buffer const * const pbuf = d->parent();
1785 return pbuf->masterBuffer();
1789 bool Buffer::isChild(Buffer * child) const
1791 return d->children_positions.find(child) != d->children_positions.end();
1795 DocIterator Buffer::firstChildPosition(Buffer const * child)
1797 Impl::BufferPositionMap::iterator it;
1798 it = d->children_positions.find(child);
1799 if (it == d->children_positions.end())
1800 return DocIterator(this);
1805 std::vector<Buffer *> Buffer::getChildren() const
1807 std::vector<Buffer *> clist;
1808 // loop over children
1809 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1810 Impl::BufferPositionMap::iterator end = d->children_positions.end();
1811 for (; it != end; ++it) {
1812 Buffer * child = const_cast<Buffer *>(it->first);
1813 clist.push_back(child);
1814 // there might be grandchildren
1815 std::vector<Buffer *> glist = child->getChildren();
1816 for (vector<Buffer *>::const_iterator git = glist.begin();
1817 git != glist.end(); ++git)
1818 clist.push_back(*git);
1824 template<typename M>
1825 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1830 typename M::iterator it = m.lower_bound(x);
1831 if (it == m.begin())
1839 MacroData const * Buffer::getBufferMacro(docstring const & name,
1840 DocIterator const & pos) const
1842 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1844 // if paragraphs have no macro context set, pos will be empty
1848 // we haven't found anything yet
1849 DocIterator bestPos = par_iterator_begin();
1850 MacroData const * bestData = 0;
1852 // find macro definitions for name
1853 Impl::NamePositionScopeMacroMap::iterator nameIt
1854 = d->macros.find(name);
1855 if (nameIt != d->macros.end()) {
1856 // find last definition in front of pos or at pos itself
1857 Impl::PositionScopeMacroMap::const_iterator it
1858 = greatest_below(nameIt->second, pos);
1859 if (it != nameIt->second.end()) {
1861 // scope ends behind pos?
1862 if (pos < it->second.first) {
1863 // Looks good, remember this. If there
1864 // is no external macro behind this,
1865 // we found the right one already.
1866 bestPos = it->first;
1867 bestData = &it->second.second;
1871 // try previous macro if there is one
1872 if (it == nameIt->second.begin())
1879 // find macros in included files
1880 Impl::PositionScopeBufferMap::const_iterator it
1881 = greatest_below(d->position_to_children, pos);
1882 if (it == d->position_to_children.end())
1883 // no children before
1887 // do we know something better (i.e. later) already?
1888 if (it->first < bestPos )
1891 // scope ends behind pos?
1892 if (pos < it->second.first) {
1893 // look for macro in external file
1894 d->macro_lock = true;
1895 MacroData const * data
1896 = it->second.second->getMacro(name, false);
1897 d->macro_lock = false;
1899 bestPos = it->first;
1905 // try previous file if there is one
1906 if (it == d->position_to_children.begin())
1911 // return the best macro we have found
1916 MacroData const * Buffer::getMacro(docstring const & name,
1917 DocIterator const & pos, bool global) const
1922 // query buffer macros
1923 MacroData const * data = getBufferMacro(name, pos);
1927 // If there is a master buffer, query that
1928 Buffer const * const pbuf = d->parent();
1930 d->macro_lock = true;
1931 MacroData const * macro = pbuf->getMacro(
1932 name, *this, false);
1933 d->macro_lock = false;
1939 data = MacroTable::globalMacros().get(name);
1948 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1950 // set scope end behind the last paragraph
1951 DocIterator scope = par_iterator_begin();
1952 scope.pit() = scope.lastpit() + 1;
1954 return getMacro(name, scope, global);
1958 MacroData const * Buffer::getMacro(docstring const & name,
1959 Buffer const & child, bool global) const
1961 // look where the child buffer is included first
1962 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
1963 if (it == d->children_positions.end())
1966 // check for macros at the inclusion position
1967 return getMacro(name, it->second, global);
1971 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
1973 pit_type lastpit = it.lastpit();
1975 // look for macros in each paragraph
1976 while (it.pit() <= lastpit) {
1977 Paragraph & par = it.paragraph();
1979 // iterate over the insets of the current paragraph
1980 InsetList const & insets = par.insetList();
1981 InsetList::const_iterator iit = insets.begin();
1982 InsetList::const_iterator end = insets.end();
1983 for (; iit != end; ++iit) {
1984 it.pos() = iit->pos;
1986 // is it a nested text inset?
1987 if (iit->inset->asInsetText()) {
1988 // Inset needs its own scope?
1989 InsetText const * itext = iit->inset->asInsetText();
1990 bool newScope = itext->isMacroScope();
1992 // scope which ends just behind the inset
1993 DocIterator insetScope = it;
1996 // collect macros in inset
1997 it.push_back(CursorSlice(*iit->inset));
1998 updateMacros(it, newScope ? insetScope : scope);
2003 // is it an external file?
2004 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2005 // get buffer of external file
2006 InsetInclude const & inset =
2007 static_cast<InsetInclude const &>(*iit->inset);
2008 d->macro_lock = true;
2009 Buffer * child = inset.getChildBuffer();
2010 d->macro_lock = false;
2014 // register its position, but only when it is
2015 // included first in the buffer
2016 if (d->children_positions.find(child) ==
2017 d->children_positions.end())
2018 d->children_positions[child] = it;
2020 // register child with its scope
2021 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
2025 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2029 MathMacroTemplate & macroTemplate =
2030 static_cast<MathMacroTemplate &>(*iit->inset);
2031 MacroContext mc(*this, it);
2032 macroTemplate.updateToContext(mc);
2035 bool valid = macroTemplate.validMacro();
2036 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2037 // then the BufferView's cursor will be invalid in
2038 // some cases which leads to crashes.
2043 d->macros[macroTemplate.name()][it] =
2044 Impl::ScopeMacro(scope, MacroData(*this, it));
2054 void Buffer::updateMacros() const
2059 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2061 // start with empty table
2063 d->children_positions.clear();
2064 d->position_to_children.clear();
2066 // Iterate over buffer, starting with first paragraph
2067 // The scope must be bigger than any lookup DocIterator
2068 // later. For the global lookup, lastpit+1 is used, hence
2069 // we use lastpit+2 here.
2070 DocIterator it = par_iterator_begin();
2071 DocIterator outerScope = it;
2072 outerScope.pit() = outerScope.lastpit() + 2;
2073 updateMacros(it, outerScope);
2077 void Buffer::updateMacroInstances() const
2079 LYXERR(Debug::MACROS, "updateMacroInstances for "
2080 << d->filename.onlyFileName());
2081 DocIterator it = doc_iterator_begin(this);
2082 DocIterator end = doc_iterator_end(this);
2083 for (; it != end; it.forwardPos()) {
2084 // look for MathData cells in InsetMathNest insets
2085 Inset * inset = it.nextInset();
2089 InsetMath * minset = inset->asInsetMath();
2093 // update macro in all cells of the InsetMathNest
2094 DocIterator::idx_type n = minset->nargs();
2095 MacroContext mc = MacroContext(*this, it);
2096 for (DocIterator::idx_type i = 0; i < n; ++i) {
2097 MathData & data = minset->cell(i);
2098 data.updateMacros(0, mc);
2104 void Buffer::listMacroNames(MacroNameSet & macros) const
2109 d->macro_lock = true;
2111 // loop over macro names
2112 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2113 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2114 for (; nameIt != nameEnd; ++nameIt)
2115 macros.insert(nameIt->first);
2117 // loop over children
2118 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2119 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2120 for (; it != end; ++it)
2121 it->first->listMacroNames(macros);
2124 Buffer const * const pbuf = d->parent();
2126 pbuf->listMacroNames(macros);
2128 d->macro_lock = false;
2132 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2134 Buffer const * const pbuf = d->parent();
2139 pbuf->listMacroNames(names);
2142 MacroNameSet::iterator it = names.begin();
2143 MacroNameSet::iterator end = names.end();
2144 for (; it != end; ++it) {
2146 MacroData const * data =
2147 pbuf->getMacro(*it, *this, false);
2149 macros.insert(data);
2151 // we cannot access the original MathMacroTemplate anymore
2152 // here to calls validate method. So we do its work here manually.
2153 // FIXME: somehow make the template accessible here.
2154 if (data->optionals() > 0)
2155 features.require("xargs");
2161 Buffer::References & Buffer::references(docstring const & label)
2164 return const_cast<Buffer *>(masterBuffer())->references(label);
2166 RefCache::iterator it = d->ref_cache_.find(label);
2167 if (it != d->ref_cache_.end())
2168 return it->second.second;
2170 static InsetLabel const * dummy_il = 0;
2171 static References const dummy_refs;
2172 it = d->ref_cache_.insert(
2173 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2174 return it->second.second;
2178 Buffer::References const & Buffer::references(docstring const & label) const
2180 return const_cast<Buffer *>(this)->references(label);
2184 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2186 masterBuffer()->d->ref_cache_[label].first = il;
2190 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2192 return masterBuffer()->d->ref_cache_[label].first;
2196 void Buffer::clearReferenceCache() const
2199 d->ref_cache_.clear();
2203 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2206 //FIXME: This does not work for child documents yet.
2207 LASSERT(code == CITE_CODE, /**/);
2208 // Check if the label 'from' appears more than once
2209 vector<docstring> labels;
2211 BiblioInfo const & keys = masterBibInfo();
2212 BiblioInfo::const_iterator bit = keys.begin();
2213 BiblioInfo::const_iterator bend = keys.end();
2215 for (; bit != bend; ++bit)
2217 labels.push_back(bit->first);
2220 if (count(labels.begin(), labels.end(), from) > 1)
2223 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2224 if (it->lyxCode() == code) {
2225 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2226 docstring const oldValue = inset.getParam(paramName);
2227 if (oldValue == from)
2228 inset.setParam(paramName, to);
2234 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2235 pit_type par_end, bool full_source) const
2237 OutputParams runparams(¶ms().encoding());
2238 runparams.nice = true;
2239 runparams.flavor = params().useXetex ?
2240 OutputParams::XETEX : OutputParams::LATEX;
2241 runparams.linelen = lyxrc.plaintext_linelen;
2242 // No side effect of file copying and image conversion
2243 runparams.dryrun = true;
2247 os << "% " << _("Preview source code") << "\n\n";
2248 d->texrow.newline();
2249 d->texrow.newline();
2251 writeDocBookSource(os, absFileName(), runparams, false);
2253 // latex or literate
2254 writeLaTeXSource(os, string(), runparams, true, true);
2256 runparams.par_begin = par_begin;
2257 runparams.par_end = par_end;
2258 if (par_begin + 1 == par_end) {
2260 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2264 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2265 convert<docstring>(par_begin),
2266 convert<docstring>(par_end - 1))
2269 d->texrow.newline();
2270 d->texrow.newline();
2271 // output paragraphs
2273 docbookParagraphs(paragraphs(), *this, os, runparams);
2275 // latex or literate
2276 latexParagraphs(*this, text(), os, d->texrow, runparams);
2281 ErrorList & Buffer::errorList(string const & type) const
2283 static ErrorList emptyErrorList;
2284 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2285 if (I == d->errorLists.end())
2286 return emptyErrorList;
2292 void Buffer::updateTocItem(std::string const & type,
2293 DocIterator const & dit) const
2296 gui_->updateTocItem(type, dit);
2300 void Buffer::structureChanged() const
2303 gui_->structureChanged();
2307 void Buffer::errors(string const & err) const
2314 void Buffer::message(docstring const & msg) const
2321 void Buffer::setBusy(bool on) const
2328 void Buffer::setReadOnly(bool on) const
2331 d->wa_->setReadOnly(on);
2335 void Buffer::updateTitles() const
2338 d->wa_->updateTitles();
2342 void Buffer::resetAutosaveTimers() const
2345 gui_->resetAutosaveTimers();
2349 bool Buffer::hasGuiDelegate() const
2355 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2364 class AutoSaveBuffer : public ForkedProcess {
2367 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2368 : buffer_(buffer), fname_(fname) {}
2370 virtual boost::shared_ptr<ForkedProcess> clone() const
2372 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2377 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2378 from_utf8(fname_.absFilename())));
2379 return run(DontWait);
2383 virtual int generateChild();
2385 Buffer const & buffer_;
2390 int AutoSaveBuffer::generateChild()
2392 // tmp_ret will be located (usually) in /tmp
2393 // will that be a problem?
2394 // Note that this calls ForkedCalls::fork(), so it's
2395 // ok cross-platform.
2396 pid_t const pid = fork();
2397 // If you want to debug the autosave
2398 // you should set pid to -1, and comment out the fork.
2399 if (pid != 0 && pid != -1)
2402 // pid = -1 signifies that lyx was unable
2403 // to fork. But we will do the save
2405 bool failed = false;
2406 FileName const tmp_ret = FileName::tempName("lyxauto");
2407 if (!tmp_ret.empty()) {
2408 buffer_.writeFile(tmp_ret);
2409 // assume successful write of tmp_ret
2410 if (!tmp_ret.moveTo(fname_))
2416 // failed to write/rename tmp_ret so try writing direct
2417 if (!buffer_.writeFile(fname_)) {
2418 // It is dangerous to do this in the child,
2419 // but safe in the parent, so...
2420 if (pid == -1) // emit message signal.
2421 buffer_.message(_("Autosave failed!"));
2425 if (pid == 0) // we are the child so...
2434 FileName Buffer::getAutosaveFilename() const
2436 string const fpath = isUnnamed() ? lyxrc.document_path : filePath();
2437 string const fname = "#" + d->filename.onlyFileName() + "#";
2438 return makeAbsPath(fname, fpath);
2442 void Buffer::removeAutosaveFile() const
2444 FileName const f = getAutosaveFilename();
2450 // Perfect target for a thread...
2451 void Buffer::autoSave() const
2453 if (isBakClean() || isReadonly()) {
2454 // We don't save now, but we'll try again later
2455 resetAutosaveTimers();
2459 // emit message signal.
2460 message(_("Autosaving current document..."));
2461 AutoSaveBuffer autosave(*this, getAutosaveFilename());
2465 resetAutosaveTimers();
2469 string Buffer::bufferFormat() const
2475 if (params().useXetex)
2477 if (params().encoding().package() == Encoding::japanese)
2483 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2484 string & result_file) const
2486 string backend_format;
2487 OutputParams runparams(¶ms().encoding());
2488 runparams.flavor = OutputParams::LATEX;
2489 runparams.linelen = lyxrc.plaintext_linelen;
2490 vector<string> backs = backends();
2491 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2492 // Get shortest path to format
2493 Graph::EdgePath path;
2494 for (vector<string>::const_iterator it = backs.begin();
2495 it != backs.end(); ++it) {
2496 Graph::EdgePath p = theConverters().getPath(*it, format);
2497 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2498 backend_format = *it;
2503 runparams.flavor = theConverters().getFlavor(path);
2505 Alert::error(_("Couldn't export file"),
2506 bformat(_("No information for exporting the format %1$s."),
2507 formats.prettyName(format)));
2511 backend_format = format;
2512 // FIXME: Don't hardcode format names here, but use a flag
2513 if (backend_format == "pdflatex")
2514 runparams.flavor = OutputParams::PDFLATEX;
2517 string filename = latexName(false);
2518 filename = addName(temppath(), filename);
2519 filename = changeExtension(filename,
2520 formats.extension(backend_format));
2523 updateMacroInstances();
2525 // Plain text backend
2526 if (backend_format == "text")
2527 writePlaintextFile(*this, FileName(filename), runparams);
2529 else if (backend_format == "lyx")
2530 writeFile(FileName(filename));
2532 else if (isDocBook()) {
2533 runparams.nice = !put_in_tempdir;
2534 makeDocBookFile(FileName(filename), runparams);
2537 else if (backend_format == format) {
2538 runparams.nice = true;
2539 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2541 } else if (!lyxrc.tex_allows_spaces
2542 && contains(filePath(), ' ')) {
2543 Alert::error(_("File name error"),
2544 _("The directory path to the document cannot contain spaces."));
2547 runparams.nice = false;
2548 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2552 string const error_type = (format == "program")
2553 ? "Build" : bufferFormat();
2554 ErrorList & error_list = d->errorLists[error_type];
2555 string const ext = formats.extension(format);
2556 FileName const tmp_result_file(changeExtension(filename, ext));
2557 bool const success = theConverters().convert(this, FileName(filename),
2558 tmp_result_file, FileName(absFileName()), backend_format, format,
2560 // Emit the signal to show the error list.
2561 if (format != backend_format)
2566 if (put_in_tempdir) {
2567 result_file = tmp_result_file.absFilename();
2571 result_file = changeExtension(absFileName(), ext);
2572 // We need to copy referenced files (e. g. included graphics
2573 // if format == "dvi") to the result dir.
2574 vector<ExportedFile> const files =
2575 runparams.exportdata->externalFiles(format);
2576 string const dest = onlyPath(result_file);
2577 CopyStatus status = SUCCESS;
2578 for (vector<ExportedFile>::const_iterator it = files.begin();
2579 it != files.end() && status != CANCEL; ++it) {
2580 string const fmt = formats.getFormatFromFile(it->sourceName);
2581 status = copyFile(fmt, it->sourceName,
2582 makeAbsPath(it->exportName, dest),
2583 it->exportName, status == FORCE);
2585 if (status == CANCEL) {
2586 message(_("Document export cancelled."));
2587 } else if (tmp_result_file.exists()) {
2588 // Finally copy the main file
2589 status = copyFile(format, tmp_result_file,
2590 FileName(result_file), result_file,
2592 message(bformat(_("Document exported as %1$s "
2594 formats.prettyName(format),
2595 makeDisplayPath(result_file)));
2597 // This must be a dummy converter like fax (bug 1888)
2598 message(bformat(_("Document exported as %1$s"),
2599 formats.prettyName(format)));
2606 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2609 return doExport(format, put_in_tempdir, result_file);
2613 bool Buffer::preview(string const & format) const
2616 if (!doExport(format, true, result_file))
2618 return formats.view(*this, FileName(result_file), format);
2622 bool Buffer::isExportable(string const & format) const
2624 vector<string> backs = backends();
2625 for (vector<string>::const_iterator it = backs.begin();
2626 it != backs.end(); ++it)
2627 if (theConverters().isReachable(*it, format))
2633 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2635 vector<string> backs = backends();
2636 vector<Format const *> result =
2637 theConverters().getReachable(backs[0], only_viewable, true);
2638 for (vector<string>::const_iterator it = backs.begin() + 1;
2639 it != backs.end(); ++it) {
2640 vector<Format const *> r =
2641 theConverters().getReachable(*it, only_viewable, false);
2642 result.insert(result.end(), r.begin(), r.end());
2648 vector<string> Buffer::backends() const
2651 if (params().baseClass()->isTeXClassAvailable()) {
2652 v.push_back(bufferFormat());
2653 // FIXME: Don't hardcode format names here, but use a flag
2654 if (v.back() == "latex")
2655 v.push_back("pdflatex");
2657 v.push_back("text");
2663 bool Buffer::readFileHelper(FileName const & s)
2665 // File information about normal file
2667 docstring const file = makeDisplayPath(s.absFilename(), 50);
2668 docstring text = bformat(_("The specified document\n%1$s"
2669 "\ncould not be read."), file);
2670 Alert::error(_("Could not read document"), text);
2674 // Check if emergency save file exists and is newer.
2675 FileName const e(s.absFilename() + ".emergency");
2677 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2678 docstring const file = makeDisplayPath(s.absFilename(), 20);
2679 docstring const text =
2680 bformat(_("An emergency save of the document "
2682 "Recover emergency save?"), file);
2683 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2684 _("&Recover"), _("&Load Original"),
2688 // the file is not saved if we load the emergency file.
2698 // Now check if autosave file is newer.
2699 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2701 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2702 docstring const file = makeDisplayPath(s.absFilename(), 20);
2703 docstring const text =
2704 bformat(_("The backup of the document "
2705 "%1$s is newer.\n\nLoad the "
2706 "backup instead?"), file);
2707 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2708 _("&Load backup"), _("Load &original"),
2712 // the file is not saved if we load the autosave file.
2716 // Here we delete the autosave
2727 bool Buffer::loadLyXFile(FileName const & s)
2729 if (s.isReadableFile()) {
2730 if (readFileHelper(s)) {
2731 lyxvc().file_found_hook(s);
2732 if (!s.isWritable())
2737 docstring const file = makeDisplayPath(s.absFilename(), 20);
2738 // Here we probably should run
2739 if (LyXVC::file_not_found_hook(s)) {
2740 docstring const text =
2741 bformat(_("Do you want to retrieve the document"
2742 " %1$s from version control?"), file);
2743 int const ret = Alert::prompt(_("Retrieve from version control?"),
2744 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2747 // How can we know _how_ to do the checkout?
2748 // With the current VC support it has to be,
2749 // a RCS file since CVS do not have special ,v files.
2751 return loadLyXFile(s);
2759 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2761 TeXErrors::Errors::const_iterator cit = terr.begin();
2762 TeXErrors::Errors::const_iterator end = terr.end();
2764 for (; cit != end; ++cit) {
2767 int errorRow = cit->error_in_line;
2768 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2774 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2775 } while (found && id_start == id_end && pos_start == pos_end);
2777 errorList.push_back(ErrorItem(cit->error_desc,
2778 cit->error_text, id_start, pos_start, pos_end));
2783 void Buffer::setBuffersForInsets() const
2785 inset().setBuffer(const_cast<Buffer &>(*this));
2789 void Buffer::updateLabels(UpdateScope scope) const
2791 // Use the master text class also for child documents
2792 Buffer const * const master = masterBuffer();
2793 DocumentClass const & textclass = master->params().documentClass();
2795 // keep the buffers to be children in this set. If the call from the
2796 // master comes back we can see which of them were actually seen (i.e.
2797 // via an InsetInclude). The remaining ones in the set need still be updated.
2798 static std::set<Buffer const *> bufToUpdate;
2799 if (scope == UpdateMaster) {
2800 // If this is a child document start with the master
2801 if (master != this) {
2802 bufToUpdate.insert(this);
2803 master->updateLabels();
2804 // Do this here in case the master has no gui associated with it. Then,
2805 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
2809 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
2810 if (bufToUpdate.find(this) == bufToUpdate.end())
2814 // start over the counters in the master
2815 textclass.counters().reset();
2818 // update will be done below for this buffer
2819 bufToUpdate.erase(this);
2821 // update all caches
2822 clearReferenceCache();
2825 Buffer & cbuf = const_cast<Buffer &>(*this);
2827 LASSERT(!text().paragraphs().empty(), /**/);
2830 ParIterator parit = cbuf.par_iterator_begin();
2831 updateLabels(parit);
2834 // TocBackend update will be done later.
2837 cbuf.tocBackend().update();
2838 if (scope == UpdateMaster)
2839 cbuf.structureChanged();
2843 static depth_type getDepth(DocIterator const & it)
2845 depth_type depth = 0;
2846 for (size_t i = 0 ; i < it.depth() ; ++i)
2847 if (!it[i].inset().inMathed())
2848 depth += it[i].paragraph().getDepth() + 1;
2849 // remove 1 since the outer inset does not count
2853 static depth_type getItemDepth(ParIterator const & it)
2855 Paragraph const & par = *it;
2856 LabelType const labeltype = par.layout().labeltype;
2858 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
2861 // this will hold the lowest depth encountered up to now.
2862 depth_type min_depth = getDepth(it);
2863 ParIterator prev_it = it;
2866 --prev_it.top().pit();
2868 // start of nested inset: go to outer par
2870 if (prev_it.empty()) {
2871 // start of document: nothing to do
2876 // We search for the first paragraph with same label
2877 // that is not more deeply nested.
2878 Paragraph & prev_par = *prev_it;
2879 depth_type const prev_depth = getDepth(prev_it);
2880 if (labeltype == prev_par.layout().labeltype) {
2881 if (prev_depth < min_depth)
2882 return prev_par.itemdepth + 1;
2883 if (prev_depth == min_depth)
2884 return prev_par.itemdepth;
2886 min_depth = min(min_depth, prev_depth);
2887 // small optimization: if we are at depth 0, we won't
2888 // find anything else
2889 if (prev_depth == 0)
2895 static bool needEnumCounterReset(ParIterator const & it)
2897 Paragraph const & par = *it;
2898 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
2899 depth_type const cur_depth = par.getDepth();
2900 ParIterator prev_it = it;
2901 while (prev_it.pit()) {
2902 --prev_it.top().pit();
2903 Paragraph const & prev_par = *prev_it;
2904 if (prev_par.getDepth() <= cur_depth)
2905 return prev_par.layout().labeltype != LABEL_ENUMERATE;
2907 // start of nested inset: reset
2912 // set the label of a paragraph. This includes the counters.
2913 static void setLabel(Buffer const & buf, ParIterator & it)
2915 BufferParams const & bp = buf.masterBuffer()->params();
2916 DocumentClass const & textclass = bp.documentClass();
2917 Paragraph & par = it.paragraph();
2918 Layout const & layout = par.layout();
2919 Counters & counters = textclass.counters();
2921 if (par.params().startOfAppendix()) {
2922 // FIXME: only the counter corresponding to toplevel
2923 // sectionning should be reset
2925 counters.appendix(true);
2927 par.params().appendix(counters.appendix());
2929 // Compute the item depth of the paragraph
2930 par.itemdepth = getItemDepth(it);
2932 if (layout.margintype == MARGIN_MANUAL) {
2933 if (par.params().labelWidthString().empty())
2934 par.params().labelWidthString(par.translateIfPossible(layout.labelstring(), bp));
2936 par.params().labelWidthString(docstring());
2939 switch(layout.labeltype) {
2941 if (layout.toclevel <= bp.secnumdepth
2942 && (layout.latextype != LATEX_ENVIRONMENT
2943 || isFirstInSequence(it.pit(), it.plist()))) {
2944 counters.step(layout.counter);
2945 par.params().labelString(
2946 par.expandLabel(layout, bp));
2948 par.params().labelString(docstring());
2951 case LABEL_ITEMIZE: {
2952 // At some point of time we should do something more
2953 // clever here, like:
2954 // par.params().labelString(
2955 // bp.user_defined_bullet(par.itemdepth).getText());
2956 // for now, use a simple hardcoded label
2957 docstring itemlabel;
2958 switch (par.itemdepth) {
2960 itemlabel = char_type(0x2022);
2963 itemlabel = char_type(0x2013);
2966 itemlabel = char_type(0x2217);
2969 itemlabel = char_type(0x2219); // or 0x00b7
2972 par.params().labelString(itemlabel);
2976 case LABEL_ENUMERATE: {
2977 // FIXME: Yes I know this is a really, really! bad solution
2979 docstring enumcounter = from_ascii("enum");
2981 switch (par.itemdepth) {
2990 enumcounter += "iv";
2993 // not a valid enumdepth...
2997 // Maybe we have to reset the enumeration counter.
2998 if (needEnumCounterReset(it))
2999 counters.reset(enumcounter);
3001 counters.step(enumcounter);
3005 switch (par.itemdepth) {
3007 format = N_("\\arabic{enumi}.");
3010 format = N_("(\\alph{enumii})");
3013 format = N_("\\roman{enumiii}.");
3016 format = N_("\\Alph{enumiv}.");
3019 // not a valid enumdepth...
3023 par.params().labelString(counters.counterLabel(
3024 par.translateIfPossible(from_ascii(format), bp)));
3029 case LABEL_SENSITIVE: {
3030 string const & type = counters.current_float();
3031 docstring full_label;
3033 full_label = buf.B_("Senseless!!! ");
3035 docstring name = buf.B_(textclass.floats().getType(type).name());
3036 if (counters.hasCounter(from_utf8(type))) {
3037 counters.step(from_utf8(type));
3038 full_label = bformat(from_ascii("%1$s %2$s:"),
3040 counters.theCounter(from_utf8(type)));
3042 full_label = bformat(from_ascii("%1$s #:"), name);
3044 par.params().labelString(full_label);
3048 case LABEL_NO_LABEL:
3049 par.params().labelString(docstring());
3053 case LABEL_TOP_ENVIRONMENT:
3054 case LABEL_CENTERED_TOP_ENVIRONMENT:
3057 par.params().labelString(
3058 par.translateIfPossible(layout.labelstring(), bp));
3064 void Buffer::updateLabels(ParIterator & parit) const
3066 LASSERT(parit.pit() == 0, /**/);
3068 // set the position of the text in the buffer to be able
3069 // to resolve macros in it. This has nothing to do with
3070 // labels, but by putting it here we avoid implementing
3071 // a whole bunch of traversal routines just for this call.
3072 parit.text()->setMacrocontextPosition(parit);
3074 depth_type maxdepth = 0;
3075 pit_type const lastpit = parit.lastpit();
3076 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3077 // reduce depth if necessary
3078 parit->params().depth(min(parit->params().depth(), maxdepth));
3079 maxdepth = parit->getMaxDepthAfter();
3081 // set the counter for this paragraph
3082 setLabel(*this, parit);
3085 InsetList::const_iterator iit = parit->insetList().begin();
3086 InsetList::const_iterator end = parit->insetList().end();
3087 for (; iit != end; ++iit) {
3088 parit.pos() = iit->pos;
3089 iit->inset->updateLabels(parit);
3095 bool Buffer::nextWord(DocIterator & from, DocIterator & to,
3096 docstring & word) const
3098 bool inword = false;
3099 bool ignoreword = false;
3101 // Go backward a bit if needed in order to return the word currently
3102 // pointed by 'from'.
3103 while (from && from.pos() && isLetter(from))
3105 // OK, we start from here.
3107 while (to.depth()) {
3114 lang_code = to.paragraph().getFontSettings(params(),
3115 to.pos()).language()->code();
3117 // Insets like optional hyphens and ligature
3118 // break are part of a word.
3119 if (!to.paragraph().isInset(to.pos())) {
3120 char_type const c = to.paragraph().getChar(to.pos());
3125 } else { // !isLetter(cur)
3126 if (inword && !word.empty() && !ignoreword)
3138 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3139 WordLangTuple & word_lang, docstring_list & suggestions) const
3142 SpellChecker::Result res = SpellChecker::OK;
3143 SpellChecker * speller = theSpellChecker();
3144 suggestions.clear();
3146 while (nextWord(from, to, word)) {
3148 string lang_code = lyxrc.spellchecker_use_alt_lang
3149 ? lyxrc.spellchecker_alt_lang
3150 : from.paragraph().getFontSettings(params(), from.pos()).language()->code();
3151 WordLangTuple wl(word, lang_code);
3152 res = speller->check(wl);
3153 // ... just bail out if the spellchecker reports an error.
3154 if (!speller->error().empty()) {
3155 throw ExceptionMessage(WarningException,
3156 _("The spellchecker has failed."), speller->error());
3158 if (res != SpellChecker::OK && res != SpellChecker::IGNORED_WORD) {
3164 while (!(word = speller->nextMiss()).empty())
3165 suggestions.push_back(word);