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 "DispatchResult.h"
28 #include "DocIterator.h"
30 #include "ErrorList.h"
33 #include "FuncRequest.h"
34 #include "FuncStatus.h"
35 #include "InsetIterator.h"
36 #include "InsetList.h"
38 #include "LaTeXFeatures.h"
42 #include "LyXAction.h"
46 #include "output_docbook.h"
48 #include "output_latex.h"
49 #include "output_plaintext.h"
50 #include "paragraph_funcs.h"
51 #include "Paragraph.h"
52 #include "ParagraphParameters.h"
53 #include "ParIterator.h"
54 #include "PDFOptions.h"
55 #include "SpellChecker.h"
58 #include "TexStream.h"
60 #include "TextClass.h"
61 #include "TocBackend.h"
63 #include "VCBackend.h"
65 #include "WordLangTuple.h"
68 #include "insets/InsetBibitem.h"
69 #include "insets/InsetBibtex.h"
70 #include "insets/InsetInclude.h"
71 #include "insets/InsetText.h"
73 #include "mathed/MacroTable.h"
74 #include "mathed/MathMacroTemplate.h"
75 #include "mathed/MathSupport.h"
77 #include "frontends/alert.h"
78 #include "frontends/Delegates.h"
79 #include "frontends/WorkAreaManager.h"
81 #include "graphics/Previews.h"
83 #include "support/lassert.h"
84 #include "support/convert.h"
85 #include "support/debug.h"
86 #include "support/docstring_list.h"
87 #include "support/ExceptionMessage.h"
88 #include "support/FileName.h"
89 #include "support/FileNameList.h"
90 #include "support/filetools.h"
91 #include "support/ForkedCalls.h"
92 #include "support/gettext.h"
93 #include "support/gzstream.h"
94 #include "support/lstrings.h"
95 #include "support/lyxalgo.h"
96 #include "support/os.h"
97 #include "support/Package.h"
98 #include "support/Path.h"
99 #include "support/Systemcall.h"
100 #include "support/textutils.h"
101 #include "support/types.h"
103 #include <boost/bind.hpp>
104 #include <boost/shared_ptr.hpp>
116 using namespace lyx::support;
120 namespace Alert = frontend::Alert;
121 namespace os = support::os;
125 // Do not remove the comment below, so we get merge conflict in
126 // independent branches. Instead add your own.
127 int const LYX_FORMAT = 350; // jspitzm: default output format
129 typedef map<string, bool> DepClean;
130 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
132 void showPrintError(string const & name)
134 docstring str = bformat(_("Could not print the document %1$s.\n"
135 "Check that your printer is set up correctly."),
136 makeDisplayPath(name, 50));
137 Alert::error(_("Print document failed"), str);
142 class BufferSet : public std::set<Buffer const *> {};
147 Impl(Buffer & parent, FileName const & file, bool readonly);
161 mutable TexRow texrow;
163 /// need to regenerate .tex?
167 mutable bool lyx_clean;
169 /// is autosave needed?
170 mutable bool bak_clean;
172 /// is this a unnamed file (New...)?
178 /// name of the file the buffer is associated with.
181 /** Set to true only when the file is fully loaded.
182 * Used to prevent the premature generation of previews
183 * and by the citation inset.
185 bool file_fully_loaded;
188 mutable TocBackend toc_backend;
191 typedef pair<DocIterator, MacroData> ScopeMacro;
192 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
193 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
194 /// map from the macro name to the position map,
195 /// which maps the macro definition position to the scope and the MacroData.
196 NamePositionScopeMacroMap macros;
199 /// positions of child buffers in the buffer
200 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
201 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
202 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
203 /// position of children buffers in this buffer
204 BufferPositionMap children_positions;
205 /// map from children inclusion positions to their scope and their buffer
206 PositionScopeBufferMap position_to_children;
208 /// Container for all sort of Buffer dependant errors.
209 map<string, ErrorList> errorLists;
211 /// timestamp and checksum used to test if the file has been externally
212 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
214 unsigned long checksum_;
217 frontend::WorkAreaManager * wa_;
222 /// A cache for the bibfiles (including bibfiles of loaded child
223 /// documents), needed for appropriate update of natbib labels.
224 mutable support::FileNameList bibfilesCache_;
226 // FIXME The caching mechanism could be improved. At present, we have a
227 // cache for each Buffer, that caches all the bibliography info for that
228 // Buffer. A more efficient solution would be to have a global cache per
229 // file, and then to construct the Buffer's bibinfo from that.
230 /// A cache for bibliography info
231 mutable BiblioInfo bibinfo_;
232 /// whether the bibinfo cache is valid
233 bool bibinfoCacheValid_;
234 /// Cache of timestamps of .bib files
235 map<FileName, time_t> bibfileStatus_;
237 mutable RefCache ref_cache_;
239 /// our Text that should be wrapped in an InsetText
242 /// This is here to force the test to be done whenever parent_buffer
244 Buffer const * parent() const {
245 // if parent_buffer is not loaded, then it has been unloaded,
246 // which means that parent_buffer is an invalid pointer. So we
247 // set it to null in that case.
248 if (!theBufferList().isLoaded(parent_buffer))
250 return parent_buffer;
253 void setParent(Buffer const * pb) { parent_buffer = pb; }
255 /// So we can force access via the accessors.
256 mutable Buffer const * parent_buffer;
260 /// Creates the per buffer temporary directory
261 static FileName createBufferTmpDir()
264 // We are in our own directory. Why bother to mangle name?
265 // In fact I wrote this code to circumvent a problematic behaviour
266 // (bug?) of EMX mkstemp().
267 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
268 convert<string>(count++));
270 if (!tmpfl.createDirectory(0777)) {
271 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
272 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
273 from_utf8(tmpfl.absFilename())));
279 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
280 : lyx_clean(true), bak_clean(true), unnamed(false),
281 read_only(readonly_), filename(file), file_fully_loaded(false),
282 toc_backend(&parent), macro_lock(false), timestamp_(0),
283 checksum_(0), wa_(0), undo_(parent), bibinfoCacheValid_(false),
286 temppath = createBufferTmpDir();
287 lyxvc.setBuffer(&parent);
289 wa_ = new frontend::WorkAreaManager;
293 Buffer::Buffer(string const & file, bool readonly)
294 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
296 LYXERR(Debug::INFO, "Buffer::Buffer()");
298 d->inset = new InsetText(*this);
299 d->inset->setAutoBreakRows(true);
300 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
306 LYXERR(Debug::INFO, "Buffer::~Buffer()");
307 // here the buffer should take care that it is
308 // saved properly, before it goes into the void.
310 // GuiView already destroyed
313 if (d->unnamed && d->filename.extension() == "internal") {
314 // No need to do additional cleanups for internal buffer.
319 // loop over children
320 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
321 Impl::BufferPositionMap::iterator end = d->children_positions.end();
322 for (; it != end; ++it) {
323 Buffer * child = const_cast<Buffer *>(it->first);
324 // The child buffer might have been closed already.
325 if (theBufferList().isLoaded(child))
326 theBufferList().releaseChild(this, child);
329 // clear references to children in macro tables
330 d->children_positions.clear();
331 d->position_to_children.clear();
333 if (!d->temppath.destroyDirectory()) {
334 Alert::warning(_("Could not remove temporary directory"),
335 bformat(_("Could not remove the temporary directory %1$s"),
336 from_utf8(d->temppath.absFilename())));
339 // Remove any previewed LaTeX snippets associated with this buffer.
340 thePreviews().removeLoader(*this);
346 void Buffer::changed() const
353 frontend::WorkAreaManager & Buffer::workAreaManager() const
355 LASSERT(d->wa_, /**/);
360 Text & Buffer::text() const
362 return d->inset->text();
366 Inset & Buffer::inset() const
372 BufferParams & Buffer::params()
378 BufferParams const & Buffer::params() const
384 ParagraphList & Buffer::paragraphs()
386 return text().paragraphs();
390 ParagraphList const & Buffer::paragraphs() const
392 return text().paragraphs();
396 LyXVC & Buffer::lyxvc()
402 LyXVC const & Buffer::lyxvc() const
408 string const Buffer::temppath() const
410 return d->temppath.absFilename();
414 TexRow & Buffer::texrow()
420 TexRow const & Buffer::texrow() const
426 TocBackend & Buffer::tocBackend() const
428 return d->toc_backend;
432 Undo & Buffer::undo()
438 string Buffer::latexName(bool const no_path) const
440 FileName latex_name = makeLatexName(d->filename);
441 return no_path ? latex_name.onlyFileName()
442 : latex_name.absFilename();
446 string Buffer::logName(LogType * type) const
448 string const filename = latexName(false);
450 if (filename.empty()) {
456 string const path = temppath();
458 FileName const fname(addName(temppath(),
459 onlyFilename(changeExtension(filename,
461 FileName const bname(
462 addName(path, onlyFilename(
463 changeExtension(filename,
464 formats.extension("literate") + ".out"))));
466 // If no Latex log or Build log is newer, show Build log
468 if (bname.exists() &&
469 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
470 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
473 return bname.absFilename();
475 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
478 return fname.absFilename();
482 void Buffer::setReadonly(bool const flag)
484 if (d->read_only != flag) {
491 void Buffer::setFileName(string const & newfile)
493 d->filename = makeAbsPath(newfile);
494 setReadonly(d->filename.isReadOnly());
499 int Buffer::readHeader(Lexer & lex)
501 int unknown_tokens = 0;
503 int begin_header_line = -1;
505 // Initialize parameters that may be/go lacking in header:
506 params().branchlist().clear();
507 params().preamble.erase();
508 params().options.erase();
509 params().master.erase();
510 params().float_placement.erase();
511 params().paperwidth.erase();
512 params().paperheight.erase();
513 params().leftmargin.erase();
514 params().rightmargin.erase();
515 params().topmargin.erase();
516 params().bottommargin.erase();
517 params().headheight.erase();
518 params().headsep.erase();
519 params().footskip.erase();
520 params().columnsep.erase();
521 params().fontsCJK.erase();
522 params().listings_params.clear();
523 params().clearLayoutModules();
524 params().clearRemovedModules();
525 params().pdfoptions().clear();
527 for (int i = 0; i < 4; ++i) {
528 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
529 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
532 ErrorList & errorList = d->errorLists["Parse"];
541 if (token == "\\end_header")
545 if (token == "\\begin_header") {
546 begin_header_line = line;
550 LYXERR(Debug::PARSER, "Handling document header token: `"
553 string unknown = params().readToken(lex, token, d->filename.onlyPath());
554 if (!unknown.empty()) {
555 if (unknown[0] != '\\' && token == "\\textclass") {
556 Alert::warning(_("Unknown document class"),
557 bformat(_("Using the default document class, because the "
558 "class %1$s is unknown."), from_utf8(unknown)));
561 docstring const s = bformat(_("Unknown token: "
565 errorList.push_back(ErrorItem(_("Document header error"),
570 if (begin_header_line) {
571 docstring const s = _("\\begin_header is missing");
572 errorList.push_back(ErrorItem(_("Document header error"),
576 params().makeDocumentClass();
578 return unknown_tokens;
583 // changed to be public and have one parameter
584 // Returns true if "\end_document" is not read (Asger)
585 bool Buffer::readDocument(Lexer & lex)
587 ErrorList & errorList = d->errorLists["Parse"];
590 if (!lex.checkFor("\\begin_document")) {
591 docstring const s = _("\\begin_document is missing");
592 errorList.push_back(ErrorItem(_("Document header error"),
596 // we are reading in a brand new document
597 LASSERT(paragraphs().empty(), /**/);
601 if (params().outputChanges) {
602 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
603 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
604 LaTeXFeatures::isAvailable("xcolor");
606 if (!dvipost && !xcolorulem) {
607 Alert::warning(_("Changes not shown in LaTeX output"),
608 _("Changes will not be highlighted in LaTeX output, "
609 "because neither dvipost nor xcolor/ulem are installed.\n"
610 "Please install these packages or redefine "
611 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
612 } else if (!xcolorulem) {
613 Alert::warning(_("Changes not shown in LaTeX output"),
614 _("Changes will not be highlighted in LaTeX output "
615 "when using pdflatex, because xcolor and ulem are not installed.\n"
616 "Please install both packages or redefine "
617 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
621 if (!params().master.empty()) {
622 FileName const master_file = makeAbsPath(params().master,
623 onlyPath(absFileName()));
624 if (isLyXFilename(master_file.absFilename())) {
626 checkAndLoadLyXFile(master_file, true);
628 // necessary e.g. after a reload
629 // to re-register the child (bug 5873)
630 // FIXME: clean up updateMacros (here, only
631 // child registering is needed).
632 master->updateMacros();
633 // set master as master buffer, but only
634 // if we are a real child
635 if (master->isChild(this))
637 // if the master is not fully loaded
638 // it is probably just loading this
639 // child. No warning needed then.
640 else if (master->isFullyLoaded())
641 LYXERR0("The master '"
643 << "' assigned to this document ("
645 << ") does not include "
646 "this document. Ignoring the master assignment.");
652 bool const res = text().read(*this, lex, errorList, d->inset);
655 updateMacroInstances();
660 // needed to insert the selection
661 void Buffer::insertStringAsLines(ParagraphList & pars,
662 pit_type & pit, pos_type & pos,
663 Font const & fn, docstring const & str, bool autobreakrows)
667 // insert the string, don't insert doublespace
668 bool space_inserted = true;
669 for (docstring::const_iterator cit = str.begin();
670 cit != str.end(); ++cit) {
671 Paragraph & par = pars[pit];
673 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
674 breakParagraph(params(), pars, pit, pos,
675 par.layout().isEnvironment());
678 space_inserted = true;
682 // do not insert consecutive spaces if !free_spacing
683 } else if ((*cit == ' ' || *cit == '\t') &&
684 space_inserted && !par.isFreeSpacing()) {
686 } else if (*cit == '\t') {
687 if (!par.isFreeSpacing()) {
688 // tabs are like spaces here
689 par.insertChar(pos, ' ', font, params().trackChanges);
691 space_inserted = true;
693 par.insertChar(pos, *cit, font, params().trackChanges);
695 space_inserted = true;
697 } else if (!isPrintable(*cit)) {
698 // Ignore unprintables
701 // just insert the character
702 par.insertChar(pos, *cit, font, params().trackChanges);
704 space_inserted = (*cit == ' ');
711 bool Buffer::readString(string const & s)
713 params().compressed = false;
715 // remove dummy empty par
716 paragraphs().clear();
720 FileName const name = FileName::tempName("Buffer_readString");
721 switch (readFile(lex, name, true)) {
725 // We need to call lyx2lyx, so write the input to a file
726 ofstream os(name.toFilesystemEncoding().c_str());
729 return readFile(name);
739 bool Buffer::readFile(FileName const & filename)
741 FileName fname(filename);
743 params().compressed = fname.isZippedFile();
745 // remove dummy empty par
746 paragraphs().clear();
749 if (readFile(lex, fname) != success)
756 bool Buffer::isFullyLoaded() const
758 return d->file_fully_loaded;
762 void Buffer::setFullyLoaded(bool value)
764 d->file_fully_loaded = value;
768 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
771 LASSERT(!filename.empty(), /**/);
773 // the first (non-comment) token _must_ be...
774 if (!lex.checkFor("\\lyxformat")) {
775 Alert::error(_("Document format failure"),
776 bformat(_("%1$s is not a readable LyX document."),
777 from_utf8(filename.absFilename())));
783 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
784 // if present remove ".," from string.
785 size_t dot = tmp_format.find_first_of(".,");
786 //lyxerr << " dot found at " << dot << endl;
787 if (dot != string::npos)
788 tmp_format.erase(dot, 1);
789 int const file_format = convert<int>(tmp_format);
790 //lyxerr << "format: " << file_format << endl;
792 // save timestamp and checksum of the original disk file, making sure
793 // to not overwrite them with those of the file created in the tempdir
794 // when it has to be converted to the current format.
796 // Save the timestamp and checksum of disk file. If filename is an
797 // emergency file, save the timestamp and checksum of the original lyx file
798 // because isExternallyModified will check for this file. (BUG4193)
799 string diskfile = filename.absFilename();
800 if (suffixIs(diskfile, ".emergency"))
801 diskfile = diskfile.substr(0, diskfile.size() - 10);
802 saveCheckSum(FileName(diskfile));
805 if (file_format != LYX_FORMAT) {
808 // lyx2lyx would fail
811 FileName const tmpfile = FileName::tempName("Buffer_readFile");
812 if (tmpfile.empty()) {
813 Alert::error(_("Conversion failed"),
814 bformat(_("%1$s is from a different"
815 " version of LyX, but a temporary"
816 " file for converting it could"
818 from_utf8(filename.absFilename())));
821 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
822 if (lyx2lyx.empty()) {
823 Alert::error(_("Conversion script not found"),
824 bformat(_("%1$s is from a different"
825 " version of LyX, but the"
826 " conversion script lyx2lyx"
827 " could not be found."),
828 from_utf8(filename.absFilename())));
831 ostringstream command;
832 command << os::python()
833 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
834 << " -t " << convert<string>(LYX_FORMAT)
835 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
836 << ' ' << quoteName(filename.toFilesystemEncoding());
837 string const command_str = command.str();
839 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
841 cmd_ret const ret = runCommand(command_str);
842 if (ret.first != 0) {
843 Alert::error(_("Conversion script failed"),
844 bformat(_("%1$s is from a different version"
845 " of LyX, but the lyx2lyx script"
846 " failed to convert it."),
847 from_utf8(filename.absFilename())));
850 bool const ret = readFile(tmpfile);
851 // Do stuff with tmpfile name and buffer name here.
852 return ret ? success : failure;
857 if (readDocument(lex)) {
858 Alert::error(_("Document format failure"),
859 bformat(_("%1$s ended unexpectedly, which means"
860 " that it is probably corrupted."),
861 from_utf8(filename.absFilename())));
864 d->file_fully_loaded = true;
869 // Should probably be moved to somewhere else: BufferView? LyXView?
870 bool Buffer::save() const
872 // We don't need autosaves in the immediate future. (Asger)
873 resetAutosaveTimers();
875 string const encodedFilename = d->filename.toFilesystemEncoding();
878 bool madeBackup = false;
880 // make a backup if the file already exists
881 if (lyxrc.make_backup && fileName().exists()) {
882 backupName = FileName(absFileName() + '~');
883 if (!lyxrc.backupdir_path.empty()) {
884 string const mangledName =
885 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
886 backupName = FileName(addName(lyxrc.backupdir_path,
889 if (fileName().copyTo(backupName)) {
892 Alert::error(_("Backup failure"),
893 bformat(_("Cannot create backup file %1$s.\n"
894 "Please check whether the directory exists and is writeable."),
895 from_utf8(backupName.absFilename())));
896 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
900 // ask if the disk file has been externally modified (use checksum method)
901 if (fileName().exists() && isExternallyModified(checksum_method)) {
902 docstring const file = makeDisplayPath(absFileName(), 20);
903 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
904 "you want to overwrite this file?"), file);
905 int const ret = Alert::prompt(_("Overwrite modified file?"),
906 text, 1, 1, _("&Overwrite"), _("&Cancel"));
911 if (writeFile(d->filename)) {
915 // Saving failed, so backup is not backup
917 backupName.moveTo(d->filename);
923 bool Buffer::writeFile(FileName const & fname) const
925 if (d->read_only && fname == d->filename)
930 docstring const str = bformat(_("Saving document %1$s..."),
931 makeDisplayPath(fname.absFilename()));
934 if (params().compressed) {
935 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
936 retval = ofs && write(ofs);
938 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
939 retval = ofs && write(ofs);
943 message(str + _(" could not write file!"));
947 removeAutosaveFile();
949 saveCheckSum(d->filename);
950 message(str + _(" done."));
956 bool Buffer::write(ostream & ofs) const
959 // Use the standard "C" locale for file output.
960 ofs.imbue(locale::classic());
963 // The top of the file should not be written by params().
965 // write out a comment in the top of the file
966 ofs << "#LyX " << lyx_version
967 << " created this file. For more info see http://www.lyx.org/\n"
968 << "\\lyxformat " << LYX_FORMAT << "\n"
969 << "\\begin_document\n";
971 /// For each author, set 'used' to true if there is a change
972 /// by this author in the document; otherwise set it to 'false'.
973 AuthorList::Authors::const_iterator a_it = params().authors().begin();
974 AuthorList::Authors::const_iterator a_end = params().authors().end();
975 for (; a_it != a_end; ++a_it)
976 a_it->second.setUsed(false);
978 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
979 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
980 for ( ; it != end; ++it)
981 it->checkAuthors(params().authors());
983 // now write out the buffer parameters.
984 ofs << "\\begin_header\n";
985 params().writeFile(ofs);
986 ofs << "\\end_header\n";
989 ofs << "\n\\begin_body\n";
990 text().write(*this, ofs);
991 ofs << "\n\\end_body\n";
993 // Write marker that shows file is complete
994 ofs << "\\end_document" << endl;
996 // Shouldn't really be needed....
999 // how to check if close went ok?
1000 // Following is an attempt... (BE 20001011)
1002 // good() returns false if any error occured, including some
1003 // formatting error.
1004 // bad() returns true if something bad happened in the buffer,
1005 // which should include file system full errors.
1010 lyxerr << "File was not closed properly." << endl;
1017 bool Buffer::makeLaTeXFile(FileName const & fname,
1018 string const & original_path,
1019 OutputParams const & runparams_in,
1020 bool output_preamble, bool output_body) const
1022 OutputParams runparams = runparams_in;
1023 if (params().useXetex)
1024 runparams.flavor = OutputParams::XETEX;
1026 string const encoding = runparams.encoding->iconvName();
1027 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1030 try { ofs.reset(encoding); }
1031 catch (iconv_codecvt_facet_exception & e) {
1032 lyxerr << "Caught iconv exception: " << e.what() << endl;
1033 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1034 "verify that the support software for your encoding (%1$s) is "
1035 "properly installed"), from_ascii(encoding)));
1038 if (!openFileWrite(ofs, fname))
1041 //TexStream ts(ofs.rdbuf(), &texrow());
1042 ErrorList & errorList = d->errorLists["Export"];
1044 bool failed_export = false;
1047 writeLaTeXSource(ofs, original_path,
1048 runparams, output_preamble, output_body);
1050 catch (EncodingException & e) {
1051 odocstringstream ods;
1052 ods.put(e.failed_char);
1054 oss << "0x" << hex << e.failed_char << dec;
1055 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1056 " (code point %2$s)"),
1057 ods.str(), from_utf8(oss.str()));
1058 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1059 "representable in the chosen encoding.\n"
1060 "Changing the document encoding to utf8 could help."),
1061 e.par_id, e.pos, e.pos + 1));
1062 failed_export = true;
1064 catch (iconv_codecvt_facet_exception & e) {
1065 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1066 _(e.what()), -1, 0, 0));
1067 failed_export = true;
1069 catch (exception const & e) {
1070 errorList.push_back(ErrorItem(_("conversion failed"),
1071 _(e.what()), -1, 0, 0));
1072 failed_export = true;
1075 lyxerr << "Caught some really weird exception..." << endl;
1081 failed_export = true;
1082 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1086 return !failed_export;
1090 void Buffer::writeLaTeXSource(odocstream & os,
1091 string const & original_path,
1092 OutputParams const & runparams_in,
1093 bool const output_preamble, bool const output_body) const
1095 // The child documents, if any, shall be already loaded at this point.
1097 OutputParams runparams = runparams_in;
1099 // Classify the unicode characters appearing in math insets
1100 Encodings::initUnicodeMath(*this);
1102 // validate the buffer.
1103 LYXERR(Debug::LATEX, " Validating buffer...");
1104 LaTeXFeatures features(*this, params(), runparams);
1106 LYXERR(Debug::LATEX, " Buffer validation done.");
1108 // The starting paragraph of the coming rows is the
1109 // first paragraph of the document. (Asger)
1110 if (output_preamble && runparams.nice) {
1111 os << "%% LyX " << lyx_version << " created this file. "
1112 "For more info, see http://www.lyx.org/.\n"
1113 "%% Do not edit unless you really know what "
1115 d->texrow.newline();
1116 d->texrow.newline();
1118 LYXERR(Debug::INFO, "lyx document header finished");
1120 // Don't move this behind the parent_buffer=0 code below,
1121 // because then the macros will not get the right "redefinition"
1122 // flag as they don't see the parent macros which are output before.
1125 // fold macros if possible, still with parent buffer as the
1126 // macros will be put in the prefix anyway.
1127 updateMacroInstances();
1129 // There are a few differences between nice LaTeX and usual files:
1130 // usual is \batchmode and has a
1131 // special input@path to allow the including of figures
1132 // with either \input or \includegraphics (what figinsets do).
1133 // input@path is set when the actual parameter
1134 // original_path is set. This is done for usual tex-file, but not
1135 // for nice-latex-file. (Matthias 250696)
1136 // Note that input@path is only needed for something the user does
1137 // in the preamble, included .tex files or ERT, files included by
1138 // LyX work without it.
1139 if (output_preamble) {
1140 if (!runparams.nice) {
1141 // code for usual, NOT nice-latex-file
1142 os << "\\batchmode\n"; // changed
1143 // from \nonstopmode
1144 d->texrow.newline();
1146 if (!original_path.empty()) {
1148 // We don't know the encoding of inputpath
1149 docstring const inputpath = from_utf8(latex_path(original_path));
1150 os << "\\makeatletter\n"
1151 << "\\def\\input@path{{"
1152 << inputpath << "/}}\n"
1153 << "\\makeatother\n";
1154 d->texrow.newline();
1155 d->texrow.newline();
1156 d->texrow.newline();
1159 // get parent macros (if this buffer has a parent) which will be
1160 // written at the document begin further down.
1161 MacroSet parentMacros;
1162 listParentMacros(parentMacros, features);
1164 // Write the preamble
1165 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1167 runparams.use_japanese = features.isRequired("japanese");
1173 os << "\\begin{document}\n";
1174 d->texrow.newline();
1176 // output the parent macros
1177 MacroSet::iterator it = parentMacros.begin();
1178 MacroSet::iterator end = parentMacros.end();
1179 for (; it != end; ++it)
1180 (*it)->write(os, true);
1181 } // output_preamble
1183 d->texrow.start(paragraphs().begin()->id(), 0);
1185 LYXERR(Debug::INFO, "preamble finished, now the body.");
1187 // if we are doing a real file with body, even if this is the
1188 // child of some other buffer, let's cut the link here.
1189 // This happens for example if only a child document is printed.
1190 Buffer const * save_parent = 0;
1191 if (output_preamble) {
1192 save_parent = d->parent();
1197 latexParagraphs(*this, text(), os, d->texrow, runparams);
1199 // Restore the parenthood if needed
1200 if (output_preamble)
1201 d->setParent(save_parent);
1203 // add this just in case after all the paragraphs
1205 d->texrow.newline();
1207 if (output_preamble) {
1208 os << "\\end{document}\n";
1209 d->texrow.newline();
1210 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1212 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1214 runparams_in.encoding = runparams.encoding;
1216 // Just to be sure. (Asger)
1217 d->texrow.newline();
1219 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1220 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1224 bool Buffer::isLatex() const
1226 return params().documentClass().outputType() == LATEX;
1230 bool Buffer::isLiterate() const
1232 return params().documentClass().outputType() == LITERATE;
1236 bool Buffer::isDocBook() const
1238 return params().documentClass().outputType() == DOCBOOK;
1242 void Buffer::makeDocBookFile(FileName const & fname,
1243 OutputParams const & runparams,
1244 bool const body_only) const
1246 LYXERR(Debug::LATEX, "makeDocBookFile...");
1249 if (!openFileWrite(ofs, fname))
1252 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1256 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1260 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1261 OutputParams const & runparams,
1262 bool const only_body) const
1264 LaTeXFeatures features(*this, params(), runparams);
1269 DocumentClass const & tclass = params().documentClass();
1270 string const top_element = tclass.latexname();
1273 if (runparams.flavor == OutputParams::XML)
1274 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1277 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1280 if (! tclass.class_header().empty())
1281 os << from_ascii(tclass.class_header());
1282 else if (runparams.flavor == OutputParams::XML)
1283 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1284 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1286 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1288 docstring preamble = from_utf8(params().preamble);
1289 if (runparams.flavor != OutputParams::XML ) {
1290 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1291 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1292 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1293 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1296 string const name = runparams.nice
1297 ? changeExtension(absFileName(), ".sgml") : fname;
1298 preamble += features.getIncludedFiles(name);
1299 preamble += features.getLyXSGMLEntities();
1301 if (!preamble.empty()) {
1302 os << "\n [ " << preamble << " ]";
1307 string top = top_element;
1309 if (runparams.flavor == OutputParams::XML)
1310 top += params().language->code();
1312 top += params().language->code().substr(0, 2);
1315 if (!params().options.empty()) {
1317 top += params().options;
1320 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1321 << " file was created by LyX " << lyx_version
1322 << "\n See http://www.lyx.org/ for more information -->\n";
1324 params().documentClass().counters().reset();
1328 sgml::openTag(os, top);
1330 docbookParagraphs(paragraphs(), *this, os, runparams);
1331 sgml::closeTag(os, top_element);
1335 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1336 // Other flags: -wall -v0 -x
1337 int Buffer::runChktex()
1341 // get LaTeX-Filename
1342 FileName const path(temppath());
1343 string const name = addName(path.absFilename(), latexName());
1344 string const org_path = filePath();
1346 PathChanger p(path); // path to LaTeX file
1347 message(_("Running chktex..."));
1349 // Generate the LaTeX file if neccessary
1350 OutputParams runparams(¶ms().encoding());
1351 runparams.flavor = OutputParams::LATEX;
1352 runparams.nice = false;
1353 makeLaTeXFile(FileName(name), org_path, runparams);
1356 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1357 int const res = chktex.run(terr); // run chktex
1360 Alert::error(_("chktex failure"),
1361 _("Could not run chktex successfully."));
1362 } else if (res > 0) {
1363 ErrorList & errlist = d->errorLists["ChkTeX"];
1365 bufferErrors(terr, errlist);
1376 void Buffer::validate(LaTeXFeatures & features) const
1378 params().validate(features);
1382 for_each(paragraphs().begin(), paragraphs().end(),
1383 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1385 if (lyxerr.debugging(Debug::LATEX)) {
1386 features.showStruct();
1391 void Buffer::getLabelList(vector<docstring> & list) const
1393 // If this is a child document, use the parent's list instead.
1394 Buffer const * const pbuf = d->parent();
1396 pbuf->getLabelList(list);
1401 Toc & toc = d->toc_backend.toc("label");
1402 TocIterator toc_it = toc.begin();
1403 TocIterator end = toc.end();
1404 for (; toc_it != end; ++toc_it) {
1405 if (toc_it->depth() == 0)
1406 list.push_back(toc_it->str());
1411 void Buffer::updateBibfilesCache(UpdateScope scope) const
1413 // If this is a child document, use the parent's cache instead.
1414 Buffer const * const pbuf = d->parent();
1415 if (pbuf && scope != UpdateChildOnly) {
1416 pbuf->updateBibfilesCache();
1420 d->bibfilesCache_.clear();
1421 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1422 if (it->lyxCode() == BIBTEX_CODE) {
1423 InsetBibtex const & inset =
1424 static_cast<InsetBibtex const &>(*it);
1425 support::FileNameList const bibfiles = inset.getBibFiles();
1426 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1429 } else if (it->lyxCode() == INCLUDE_CODE) {
1430 InsetInclude & inset =
1431 static_cast<InsetInclude &>(*it);
1432 inset.updateBibfilesCache();
1433 support::FileNameList const & bibfiles =
1434 inset.getBibfilesCache();
1435 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1440 // the bibinfo cache is now invalid
1441 d->bibinfoCacheValid_ = false;
1445 void Buffer::invalidateBibinfoCache()
1447 d->bibinfoCacheValid_ = false;
1451 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1453 // If this is a child document, use the parent's cache instead.
1454 Buffer const * const pbuf = d->parent();
1455 if (pbuf && scope != UpdateChildOnly)
1456 return pbuf->getBibfilesCache();
1458 // We update the cache when first used instead of at loading time.
1459 if (d->bibfilesCache_.empty())
1460 const_cast<Buffer *>(this)->updateBibfilesCache(scope);
1462 return d->bibfilesCache_;
1466 BiblioInfo const & Buffer::masterBibInfo() const
1468 // if this is a child document and the parent is already loaded
1469 // use the parent's list instead [ale990412]
1470 Buffer const * const tmp = masterBuffer();
1473 return tmp->masterBibInfo();
1474 return localBibInfo();
1478 BiblioInfo const & Buffer::localBibInfo() const
1480 if (d->bibinfoCacheValid_) {
1481 support::FileNameList const & bibfilesCache = getBibfilesCache();
1482 // compare the cached timestamps with the actual ones.
1483 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1484 support::FileNameList::const_iterator en = bibfilesCache.end();
1485 for (; ei != en; ++ ei) {
1486 time_t lastw = ei->lastModified();
1487 if (lastw != d->bibfileStatus_[*ei]) {
1488 d->bibinfoCacheValid_ = false;
1489 d->bibfileStatus_[*ei] = lastw;
1495 if (!d->bibinfoCacheValid_) {
1496 d->bibinfo_.clear();
1497 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1498 it->fillWithBibKeys(d->bibinfo_, it);
1499 d->bibinfoCacheValid_ = true;
1505 bool Buffer::isDepClean(string const & name) const
1507 DepClean::const_iterator const it = d->dep_clean.find(name);
1508 if (it == d->dep_clean.end())
1514 void Buffer::markDepClean(string const & name)
1516 d->dep_clean[name] = true;
1520 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1522 switch (cmd.action) {
1523 case LFUN_BUFFER_EXPORT: {
1524 docstring const arg = cmd.argument();
1525 bool enable = arg == "custom" || isExportable(to_utf8(arg));
1527 flag.message(bformat(
1528 _("Don't know how to export to format: %1$s"), arg));
1529 flag.setEnabled(enable);
1533 case LFUN_BRANCH_ACTIVATE:
1534 case LFUN_BRANCH_DEACTIVATE: {
1535 BranchList const & branchList = params().branchlist();
1536 docstring const branchName = cmd.argument();
1537 flag.setEnabled(!branchName.empty()
1538 && branchList.find(branchName));
1542 case LFUN_BUFFER_PRINT:
1543 // if no Buffer is present, then of course we won't be called!
1544 flag.setEnabled(true);
1554 void Buffer::dispatch(string const & command, DispatchResult & result)
1556 return dispatch(lyxaction.lookupFunc(command), result);
1560 // NOTE We can end up here even if we have no GUI, because we are called
1561 // by LyX::exec to handled command-line requests. So we may need to check
1562 // whether we have a GUI or not. The boolean use_gui holds this information.
1563 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1565 // We'll set this back to false if need be.
1566 bool dispatched = true;
1568 switch (func.action) {
1569 case LFUN_BUFFER_EXPORT: {
1570 bool success = doExport(to_utf8(func.argument()), false);
1571 dr.setError(success);
1573 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
1578 case LFUN_BRANCH_ACTIVATE:
1579 case LFUN_BRANCH_DEACTIVATE: {
1580 BranchList & branchList = params().branchlist();
1581 docstring const branchName = func.argument();
1582 // the case without a branch name is handled elsewhere
1583 if (branchName.empty()) {
1587 Branch * branch = branchList.find(branchName);
1589 LYXERR0("Branch " << branchName << " does not exist.");
1591 docstring const msg =
1592 bformat(_("Branch \"%1$s\" does not exist."), branchName);
1595 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1597 dr.update(Update::Force);
1602 case LFUN_BUFFER_PRINT: {
1603 // we'll assume there's a problem until we succeed
1605 string target = func.getArg(0);
1606 string target_name = func.getArg(1);
1607 string command = func.getArg(2);
1610 || target_name.empty()
1611 || command.empty()) {
1612 LYXERR0("Unable to parse " << func.argument());
1613 docstring const msg =
1614 bformat(_("Unable to parse \"%1$s\""), func.argument());
1618 if (target != "printer" && target != "file") {
1619 LYXERR0("Unrecognized target \"" << target << '"');
1620 docstring const msg =
1621 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
1626 if (!doExport("dvi", true)) {
1627 showPrintError(absFileName());
1628 dr.setMessage(_("Error exporting to DVI."));
1632 // Push directory path.
1633 string const path = temppath();
1634 // Prevent the compiler from optimizing away p
1638 // there are three cases here:
1639 // 1. we print to a file
1640 // 2. we print directly to a printer
1641 // 3. we print using a spool command (print to file first)
1644 string const dviname = changeExtension(latexName(true), "dvi");
1646 if (target == "printer") {
1647 if (!lyxrc.print_spool_command.empty()) {
1648 // case 3: print using a spool
1649 string const psname = changeExtension(dviname,".ps");
1650 command += ' ' + lyxrc.print_to_file
1653 + quoteName(dviname);
1655 string command2 = lyxrc.print_spool_command + ' ';
1656 if (target_name != "default") {
1657 command2 += lyxrc.print_spool_printerprefix
1661 command2 += quoteName(psname);
1663 // If successful, then spool command
1664 res = one.startscript(Systemcall::Wait, command);
1667 // If there's no GUI, we have to wait on this command. Otherwise,
1668 // LyX deletes the temporary directory, and with it the spooled
1669 // file, before it can be printed!!
1670 Systemcall::Starttype stype = use_gui ?
1671 Systemcall::DontWait : Systemcall::Wait;
1672 res = one.startscript(stype, command2);
1675 // case 2: print directly to a printer
1676 if (target_name != "default")
1677 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
1679 Systemcall::Starttype stype = use_gui ?
1680 Systemcall::DontWait : Systemcall::Wait;
1681 res = one.startscript(stype, command + quoteName(dviname));
1685 // case 1: print to a file
1686 FileName const filename(makeAbsPath(target_name, filePath()));
1687 FileName const dvifile(makeAbsPath(dviname, path));
1688 if (filename.exists()) {
1689 docstring text = bformat(
1690 _("The file %1$s already exists.\n\n"
1691 "Do you want to overwrite that file?"),
1692 makeDisplayPath(filename.absFilename()));
1693 if (Alert::prompt(_("Overwrite file?"),
1694 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
1697 command += ' ' + lyxrc.print_to_file
1698 + quoteName(filename.toFilesystemEncoding())
1700 + quoteName(dvifile.toFilesystemEncoding());
1702 Systemcall::Starttype stype = use_gui ?
1703 Systemcall::DontWait : Systemcall::Wait;
1704 res = one.startscript(stype, command);
1710 dr.setMessage(_("Error running external commands."));
1711 showPrintError(absFileName());
1720 dr.dispatched(dispatched);
1724 void Buffer::changeLanguage(Language const * from, Language const * to)
1726 LASSERT(from, /**/);
1729 for_each(par_iterator_begin(),
1731 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1735 bool Buffer::isMultiLingual() const
1737 ParConstIterator end = par_iterator_end();
1738 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1739 if (it->isMultiLingual(params()))
1746 DocIterator Buffer::getParFromID(int const id) const
1748 Buffer * buf = const_cast<Buffer *>(this);
1750 // John says this is called with id == -1 from undo
1751 lyxerr << "getParFromID(), id: " << id << endl;
1752 return doc_iterator_end(buf);
1755 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
1756 if (it.paragraph().id() == id)
1759 return doc_iterator_end(buf);
1763 bool Buffer::hasParWithID(int const id) const
1765 return !getParFromID(id).atEnd();
1769 ParIterator Buffer::par_iterator_begin()
1771 return ParIterator(doc_iterator_begin(this));
1775 ParIterator Buffer::par_iterator_end()
1777 return ParIterator(doc_iterator_end(this));
1781 ParConstIterator Buffer::par_iterator_begin() const
1783 return ParConstIterator(doc_iterator_begin(this));
1787 ParConstIterator Buffer::par_iterator_end() const
1789 return ParConstIterator(doc_iterator_end(this));
1793 Language const * Buffer::language() const
1795 return params().language;
1799 docstring const Buffer::B_(string const & l10n) const
1801 return params().B_(l10n);
1805 bool Buffer::isClean() const
1807 return d->lyx_clean;
1811 bool Buffer::isBakClean() const
1813 return d->bak_clean;
1817 bool Buffer::isExternallyModified(CheckMethod method) const
1819 LASSERT(d->filename.exists(), /**/);
1820 // if method == timestamp, check timestamp before checksum
1821 return (method == checksum_method
1822 || d->timestamp_ != d->filename.lastModified())
1823 && d->checksum_ != d->filename.checksum();
1827 void Buffer::saveCheckSum(FileName const & file) const
1829 if (file.exists()) {
1830 d->timestamp_ = file.lastModified();
1831 d->checksum_ = file.checksum();
1833 // in the case of save to a new file.
1840 void Buffer::markClean() const
1842 if (!d->lyx_clean) {
1843 d->lyx_clean = true;
1846 // if the .lyx file has been saved, we don't need an
1848 d->bak_clean = true;
1852 void Buffer::markBakClean() const
1854 d->bak_clean = true;
1858 void Buffer::setUnnamed(bool flag)
1864 bool Buffer::isUnnamed() const
1870 // FIXME: this function should be moved to buffer_pimpl.C
1871 void Buffer::markDirty()
1874 d->lyx_clean = false;
1877 d->bak_clean = false;
1879 DepClean::iterator it = d->dep_clean.begin();
1880 DepClean::const_iterator const end = d->dep_clean.end();
1882 for (; it != end; ++it)
1887 FileName Buffer::fileName() const
1893 string Buffer::absFileName() const
1895 return d->filename.absFilename();
1899 string Buffer::filePath() const
1901 return d->filename.onlyPath().absFilename() + "/";
1905 bool Buffer::isReadonly() const
1907 return d->read_only;
1911 void Buffer::setParent(Buffer const * buffer)
1913 // Avoids recursive include.
1914 d->setParent(buffer == this ? 0 : buffer);
1919 Buffer const * Buffer::parent() const
1925 void Buffer::collectRelatives(BufferSet & bufs) const
1929 parent()->collectRelatives(bufs);
1931 // loop over children
1932 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1933 Impl::BufferPositionMap::iterator end = d->children_positions.end();
1934 for (; it != end; ++it)
1935 bufs.insert(const_cast<Buffer *>(it->first));
1939 std::vector<Buffer const *> Buffer::allRelatives() const
1942 collectRelatives(bufs);
1943 BufferSet::iterator it = bufs.begin();
1944 std::vector<Buffer const *> ret;
1945 for (; it != bufs.end(); ++it)
1951 Buffer const * Buffer::masterBuffer() const
1953 Buffer const * const pbuf = d->parent();
1957 return pbuf->masterBuffer();
1961 bool Buffer::isChild(Buffer * child) const
1963 return d->children_positions.find(child) != d->children_positions.end();
1967 DocIterator Buffer::firstChildPosition(Buffer const * child)
1969 Impl::BufferPositionMap::iterator it;
1970 it = d->children_positions.find(child);
1971 if (it == d->children_positions.end())
1972 return DocIterator(this);
1977 std::vector<Buffer *> Buffer::getChildren() const
1979 std::vector<Buffer *> clist;
1980 // loop over children
1981 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1982 Impl::BufferPositionMap::iterator end = d->children_positions.end();
1983 for (; it != end; ++it) {
1984 Buffer * child = const_cast<Buffer *>(it->first);
1985 clist.push_back(child);
1986 // there might be grandchildren
1987 std::vector<Buffer *> glist = child->getChildren();
1988 for (vector<Buffer *>::const_iterator git = glist.begin();
1989 git != glist.end(); ++git)
1990 clist.push_back(*git);
1996 template<typename M>
1997 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
2002 typename M::iterator it = m.lower_bound(x);
2003 if (it == m.begin())
2011 MacroData const * Buffer::getBufferMacro(docstring const & name,
2012 DocIterator const & pos) const
2014 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2016 // if paragraphs have no macro context set, pos will be empty
2020 // we haven't found anything yet
2021 DocIterator bestPos = par_iterator_begin();
2022 MacroData const * bestData = 0;
2024 // find macro definitions for name
2025 Impl::NamePositionScopeMacroMap::iterator nameIt
2026 = d->macros.find(name);
2027 if (nameIt != d->macros.end()) {
2028 // find last definition in front of pos or at pos itself
2029 Impl::PositionScopeMacroMap::const_iterator it
2030 = greatest_below(nameIt->second, pos);
2031 if (it != nameIt->second.end()) {
2033 // scope ends behind pos?
2034 if (pos < it->second.first) {
2035 // Looks good, remember this. If there
2036 // is no external macro behind this,
2037 // we found the right one already.
2038 bestPos = it->first;
2039 bestData = &it->second.second;
2043 // try previous macro if there is one
2044 if (it == nameIt->second.begin())
2051 // find macros in included files
2052 Impl::PositionScopeBufferMap::const_iterator it
2053 = greatest_below(d->position_to_children, pos);
2054 if (it == d->position_to_children.end())
2055 // no children before
2059 // do we know something better (i.e. later) already?
2060 if (it->first < bestPos )
2063 // scope ends behind pos?
2064 if (pos < it->second.first) {
2065 // look for macro in external file
2066 d->macro_lock = true;
2067 MacroData const * data
2068 = it->second.second->getMacro(name, false);
2069 d->macro_lock = false;
2071 bestPos = it->first;
2077 // try previous file if there is one
2078 if (it == d->position_to_children.begin())
2083 // return the best macro we have found
2088 MacroData const * Buffer::getMacro(docstring const & name,
2089 DocIterator const & pos, bool global) const
2094 // query buffer macros
2095 MacroData const * data = getBufferMacro(name, pos);
2099 // If there is a master buffer, query that
2100 Buffer const * const pbuf = d->parent();
2102 d->macro_lock = true;
2103 MacroData const * macro = pbuf->getMacro(
2104 name, *this, false);
2105 d->macro_lock = false;
2111 data = MacroTable::globalMacros().get(name);
2120 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2122 // set scope end behind the last paragraph
2123 DocIterator scope = par_iterator_begin();
2124 scope.pit() = scope.lastpit() + 1;
2126 return getMacro(name, scope, global);
2130 MacroData const * Buffer::getMacro(docstring const & name,
2131 Buffer const & child, bool global) const
2133 // look where the child buffer is included first
2134 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2135 if (it == d->children_positions.end())
2138 // check for macros at the inclusion position
2139 return getMacro(name, it->second, global);
2143 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
2145 pit_type lastpit = it.lastpit();
2147 // look for macros in each paragraph
2148 while (it.pit() <= lastpit) {
2149 Paragraph & par = it.paragraph();
2151 // iterate over the insets of the current paragraph
2152 InsetList const & insets = par.insetList();
2153 InsetList::const_iterator iit = insets.begin();
2154 InsetList::const_iterator end = insets.end();
2155 for (; iit != end; ++iit) {
2156 it.pos() = iit->pos;
2158 // is it a nested text inset?
2159 if (iit->inset->asInsetText()) {
2160 // Inset needs its own scope?
2161 InsetText const * itext = iit->inset->asInsetText();
2162 bool newScope = itext->isMacroScope();
2164 // scope which ends just behind the inset
2165 DocIterator insetScope = it;
2168 // collect macros in inset
2169 it.push_back(CursorSlice(*iit->inset));
2170 updateMacros(it, newScope ? insetScope : scope);
2175 // is it an external file?
2176 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2177 // get buffer of external file
2178 InsetInclude const & inset =
2179 static_cast<InsetInclude const &>(*iit->inset);
2180 d->macro_lock = true;
2181 Buffer * child = inset.getChildBuffer();
2182 d->macro_lock = false;
2186 // register its position, but only when it is
2187 // included first in the buffer
2188 if (d->children_positions.find(child) ==
2189 d->children_positions.end())
2190 d->children_positions[child] = it;
2192 // register child with its scope
2193 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
2197 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2201 MathMacroTemplate & macroTemplate =
2202 static_cast<MathMacroTemplate &>(*iit->inset);
2203 MacroContext mc(*this, it);
2204 macroTemplate.updateToContext(mc);
2207 bool valid = macroTemplate.validMacro();
2208 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2209 // then the BufferView's cursor will be invalid in
2210 // some cases which leads to crashes.
2215 d->macros[macroTemplate.name()][it] =
2216 Impl::ScopeMacro(scope, MacroData(*this, it));
2226 void Buffer::updateMacros() const
2231 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2233 // start with empty table
2235 d->children_positions.clear();
2236 d->position_to_children.clear();
2238 // Iterate over buffer, starting with first paragraph
2239 // The scope must be bigger than any lookup DocIterator
2240 // later. For the global lookup, lastpit+1 is used, hence
2241 // we use lastpit+2 here.
2242 DocIterator it = par_iterator_begin();
2243 DocIterator outerScope = it;
2244 outerScope.pit() = outerScope.lastpit() + 2;
2245 updateMacros(it, outerScope);
2249 void Buffer::updateMacroInstances() const
2251 LYXERR(Debug::MACROS, "updateMacroInstances for "
2252 << d->filename.onlyFileName());
2253 DocIterator it = doc_iterator_begin(this);
2254 DocIterator end = doc_iterator_end(this);
2255 for (; it != end; it.forwardPos()) {
2256 // look for MathData cells in InsetMathNest insets
2257 Inset * inset = it.nextInset();
2261 InsetMath * minset = inset->asInsetMath();
2265 // update macro in all cells of the InsetMathNest
2266 DocIterator::idx_type n = minset->nargs();
2267 MacroContext mc = MacroContext(*this, it);
2268 for (DocIterator::idx_type i = 0; i < n; ++i) {
2269 MathData & data = minset->cell(i);
2270 data.updateMacros(0, mc);
2276 void Buffer::listMacroNames(MacroNameSet & macros) const
2281 d->macro_lock = true;
2283 // loop over macro names
2284 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2285 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2286 for (; nameIt != nameEnd; ++nameIt)
2287 macros.insert(nameIt->first);
2289 // loop over children
2290 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2291 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2292 for (; it != end; ++it)
2293 it->first->listMacroNames(macros);
2296 Buffer const * const pbuf = d->parent();
2298 pbuf->listMacroNames(macros);
2300 d->macro_lock = false;
2304 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2306 Buffer const * const pbuf = d->parent();
2311 pbuf->listMacroNames(names);
2314 MacroNameSet::iterator it = names.begin();
2315 MacroNameSet::iterator end = names.end();
2316 for (; it != end; ++it) {
2318 MacroData const * data =
2319 pbuf->getMacro(*it, *this, false);
2321 macros.insert(data);
2323 // we cannot access the original MathMacroTemplate anymore
2324 // here to calls validate method. So we do its work here manually.
2325 // FIXME: somehow make the template accessible here.
2326 if (data->optionals() > 0)
2327 features.require("xargs");
2333 Buffer::References & Buffer::references(docstring const & label)
2336 return const_cast<Buffer *>(masterBuffer())->references(label);
2338 RefCache::iterator it = d->ref_cache_.find(label);
2339 if (it != d->ref_cache_.end())
2340 return it->second.second;
2342 static InsetLabel const * dummy_il = 0;
2343 static References const dummy_refs;
2344 it = d->ref_cache_.insert(
2345 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2346 return it->second.second;
2350 Buffer::References const & Buffer::references(docstring const & label) const
2352 return const_cast<Buffer *>(this)->references(label);
2356 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2358 masterBuffer()->d->ref_cache_[label].first = il;
2362 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2364 return masterBuffer()->d->ref_cache_[label].first;
2368 void Buffer::clearReferenceCache() const
2371 d->ref_cache_.clear();
2375 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2378 //FIXME: This does not work for child documents yet.
2379 LASSERT(code == CITE_CODE, /**/);
2380 // Check if the label 'from' appears more than once
2381 vector<docstring> labels;
2383 BiblioInfo const & keys = masterBibInfo();
2384 BiblioInfo::const_iterator bit = keys.begin();
2385 BiblioInfo::const_iterator bend = keys.end();
2387 for (; bit != bend; ++bit)
2389 labels.push_back(bit->first);
2392 if (count(labels.begin(), labels.end(), from) > 1)
2395 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2396 if (it->lyxCode() == code) {
2397 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2398 docstring const oldValue = inset.getParam(paramName);
2399 if (oldValue == from)
2400 inset.setParam(paramName, to);
2406 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2407 pit_type par_end, bool full_source) const
2409 OutputParams runparams(¶ms().encoding());
2410 runparams.nice = true;
2411 runparams.flavor = params().useXetex ?
2412 OutputParams::XETEX : OutputParams::LATEX;
2413 runparams.linelen = lyxrc.plaintext_linelen;
2414 // No side effect of file copying and image conversion
2415 runparams.dryrun = true;
2419 os << "% " << _("Preview source code") << "\n\n";
2420 d->texrow.newline();
2421 d->texrow.newline();
2423 writeDocBookSource(os, absFileName(), runparams, false);
2425 // latex or literate
2426 writeLaTeXSource(os, string(), runparams, true, true);
2428 runparams.par_begin = par_begin;
2429 runparams.par_end = par_end;
2430 if (par_begin + 1 == par_end) {
2432 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2436 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2437 convert<docstring>(par_begin),
2438 convert<docstring>(par_end - 1))
2441 d->texrow.newline();
2442 d->texrow.newline();
2443 // output paragraphs
2445 docbookParagraphs(paragraphs(), *this, os, runparams);
2447 // latex or literate
2448 latexParagraphs(*this, text(), os, d->texrow, runparams);
2453 ErrorList & Buffer::errorList(string const & type) const
2455 static ErrorList emptyErrorList;
2456 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2457 if (I == d->errorLists.end())
2458 return emptyErrorList;
2464 void Buffer::updateTocItem(std::string const & type,
2465 DocIterator const & dit) const
2468 gui_->updateTocItem(type, dit);
2472 void Buffer::structureChanged() const
2475 gui_->structureChanged();
2479 void Buffer::errors(string const & err) const
2486 void Buffer::message(docstring const & msg) const
2493 void Buffer::setBusy(bool on) const
2500 void Buffer::setReadOnly(bool on) const
2503 d->wa_->setReadOnly(on);
2507 void Buffer::updateTitles() const
2510 d->wa_->updateTitles();
2514 void Buffer::resetAutosaveTimers() const
2517 gui_->resetAutosaveTimers();
2521 bool Buffer::hasGuiDelegate() const
2527 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2536 class AutoSaveBuffer : public ForkedProcess {
2539 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2540 : buffer_(buffer), fname_(fname) {}
2542 virtual boost::shared_ptr<ForkedProcess> clone() const
2544 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2549 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2550 from_utf8(fname_.absFilename())));
2551 return run(DontWait);
2555 virtual int generateChild();
2557 Buffer const & buffer_;
2562 int AutoSaveBuffer::generateChild()
2564 // tmp_ret will be located (usually) in /tmp
2565 // will that be a problem?
2566 // Note that this calls ForkedCalls::fork(), so it's
2567 // ok cross-platform.
2568 pid_t const pid = fork();
2569 // If you want to debug the autosave
2570 // you should set pid to -1, and comment out the fork.
2571 if (pid != 0 && pid != -1)
2574 // pid = -1 signifies that lyx was unable
2575 // to fork. But we will do the save
2577 bool failed = false;
2578 FileName const tmp_ret = FileName::tempName("lyxauto");
2579 if (!tmp_ret.empty()) {
2580 buffer_.writeFile(tmp_ret);
2581 // assume successful write of tmp_ret
2582 if (!tmp_ret.moveTo(fname_))
2588 // failed to write/rename tmp_ret so try writing direct
2589 if (!buffer_.writeFile(fname_)) {
2590 // It is dangerous to do this in the child,
2591 // but safe in the parent, so...
2592 if (pid == -1) // emit message signal.
2593 buffer_.message(_("Autosave failed!"));
2597 if (pid == 0) // we are the child so...
2606 FileName Buffer::getAutosaveFilename() const
2608 string const fpath = isUnnamed() ? lyxrc.document_path : filePath();
2609 string const fname = "#" + d->filename.onlyFileName() + "#";
2610 return makeAbsPath(fname, fpath);
2614 void Buffer::removeAutosaveFile() const
2616 FileName const f = getAutosaveFilename();
2622 // Perfect target for a thread...
2623 void Buffer::autoSave() const
2625 if (isBakClean() || isReadonly()) {
2626 // We don't save now, but we'll try again later
2627 resetAutosaveTimers();
2631 // emit message signal.
2632 message(_("Autosaving current document..."));
2633 AutoSaveBuffer autosave(*this, getAutosaveFilename());
2637 resetAutosaveTimers();
2641 string Buffer::bufferFormat() const
2647 if (params().useXetex)
2649 if (params().encoding().package() == Encoding::japanese)
2655 string Buffer::getDefaultOutputFormat() const
2657 if (!params().defaultOutputFormat.empty()
2658 && params().defaultOutputFormat != "default")
2659 return params().defaultOutputFormat;
2660 typedef vector<Format const *> Formats;
2661 Formats formats = exportableFormats(true);
2664 || params().useXetex
2665 || params().encoding().package() == Encoding::japanese) {
2666 if (formats.empty())
2668 // return the first we find
2669 return formats.front()->name();
2671 return lyxrc.default_view_format;
2676 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2677 string & result_file) const
2679 string backend_format;
2680 OutputParams runparams(¶ms().encoding());
2681 runparams.flavor = OutputParams::LATEX;
2682 runparams.linelen = lyxrc.plaintext_linelen;
2683 vector<string> backs = backends();
2684 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2685 // Get shortest path to format
2686 Graph::EdgePath path;
2687 for (vector<string>::const_iterator it = backs.begin();
2688 it != backs.end(); ++it) {
2689 Graph::EdgePath p = theConverters().getPath(*it, format);
2690 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2691 backend_format = *it;
2696 runparams.flavor = theConverters().getFlavor(path);
2698 Alert::error(_("Couldn't export file"),
2699 bformat(_("No information for exporting the format %1$s."),
2700 formats.prettyName(format)));
2704 backend_format = format;
2705 // FIXME: Don't hardcode format names here, but use a flag
2706 if (backend_format == "pdflatex")
2707 runparams.flavor = OutputParams::PDFLATEX;
2710 string filename = latexName(false);
2711 filename = addName(temppath(), filename);
2712 filename = changeExtension(filename,
2713 formats.extension(backend_format));
2716 updateMacroInstances();
2718 // Plain text backend
2719 if (backend_format == "text")
2720 writePlaintextFile(*this, FileName(filename), runparams);
2722 else if (backend_format == "lyx")
2723 writeFile(FileName(filename));
2725 else if (isDocBook()) {
2726 runparams.nice = !put_in_tempdir;
2727 makeDocBookFile(FileName(filename), runparams);
2730 else if (backend_format == format) {
2731 runparams.nice = true;
2732 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2734 } else if (!lyxrc.tex_allows_spaces
2735 && contains(filePath(), ' ')) {
2736 Alert::error(_("File name error"),
2737 _("The directory path to the document cannot contain spaces."));
2740 runparams.nice = false;
2741 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2745 string const error_type = (format == "program")
2746 ? "Build" : bufferFormat();
2747 ErrorList & error_list = d->errorLists[error_type];
2748 string const ext = formats.extension(format);
2749 FileName const tmp_result_file(changeExtension(filename, ext));
2750 bool const success = theConverters().convert(this, FileName(filename),
2751 tmp_result_file, FileName(absFileName()), backend_format, format,
2753 // Emit the signal to show the error list.
2754 if (format != backend_format)
2759 if (put_in_tempdir) {
2760 result_file = tmp_result_file.absFilename();
2764 result_file = changeExtension(absFileName(), ext);
2765 // We need to copy referenced files (e. g. included graphics
2766 // if format == "dvi") to the result dir.
2767 vector<ExportedFile> const files =
2768 runparams.exportdata->externalFiles(format);
2769 string const dest = onlyPath(result_file);
2770 CopyStatus status = SUCCESS;
2771 for (vector<ExportedFile>::const_iterator it = files.begin();
2772 it != files.end() && status != CANCEL; ++it) {
2773 string const fmt = formats.getFormatFromFile(it->sourceName);
2774 status = copyFile(fmt, it->sourceName,
2775 makeAbsPath(it->exportName, dest),
2776 it->exportName, status == FORCE);
2778 if (status == CANCEL) {
2779 message(_("Document export cancelled."));
2780 } else if (tmp_result_file.exists()) {
2781 // Finally copy the main file
2782 status = copyFile(format, tmp_result_file,
2783 FileName(result_file), result_file,
2785 message(bformat(_("Document exported as %1$s "
2787 formats.prettyName(format),
2788 makeDisplayPath(result_file)));
2790 // This must be a dummy converter like fax (bug 1888)
2791 message(bformat(_("Document exported as %1$s"),
2792 formats.prettyName(format)));
2799 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2802 return doExport(format, put_in_tempdir, result_file);
2806 bool Buffer::preview(string const & format) const
2809 if (!doExport(format, true, result_file))
2811 return formats.view(*this, FileName(result_file), format);
2815 bool Buffer::isExportable(string const & format) const
2817 vector<string> backs = backends();
2818 for (vector<string>::const_iterator it = backs.begin();
2819 it != backs.end(); ++it)
2820 if (theConverters().isReachable(*it, format))
2826 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2828 vector<string> backs = backends();
2829 vector<Format const *> result =
2830 theConverters().getReachable(backs[0], only_viewable, true);
2831 for (vector<string>::const_iterator it = backs.begin() + 1;
2832 it != backs.end(); ++it) {
2833 vector<Format const *> r =
2834 theConverters().getReachable(*it, only_viewable, false);
2835 result.insert(result.end(), r.begin(), r.end());
2841 vector<string> Buffer::backends() const
2844 if (params().baseClass()->isTeXClassAvailable()) {
2845 v.push_back(bufferFormat());
2846 // FIXME: Don't hardcode format names here, but use a flag
2847 if (v.back() == "latex")
2848 v.push_back("pdflatex");
2850 v.push_back("text");
2856 bool Buffer::readFileHelper(FileName const & s)
2858 // File information about normal file
2860 docstring const file = makeDisplayPath(s.absFilename(), 50);
2861 docstring text = bformat(_("The specified document\n%1$s"
2862 "\ncould not be read."), file);
2863 Alert::error(_("Could not read document"), text);
2867 // Check if emergency save file exists and is newer.
2868 FileName const e(s.absFilename() + ".emergency");
2870 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2871 docstring const file = makeDisplayPath(s.absFilename(), 20);
2872 docstring const text =
2873 bformat(_("An emergency save of the document "
2875 "Recover emergency save?"), file);
2876 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2877 _("&Recover"), _("&Load Original"),
2881 // the file is not saved if we load the emergency file.
2891 // Now check if autosave file is newer.
2892 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2894 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2895 docstring const file = makeDisplayPath(s.absFilename(), 20);
2896 docstring const text =
2897 bformat(_("The backup of the document "
2898 "%1$s is newer.\n\nLoad the "
2899 "backup instead?"), file);
2900 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2901 _("&Load backup"), _("Load &original"),
2905 // the file is not saved if we load the autosave file.
2909 // Here we delete the autosave
2920 bool Buffer::loadLyXFile(FileName const & s)
2922 if (s.isReadableFile()) {
2923 if (readFileHelper(s)) {
2924 lyxvc().file_found_hook(s);
2925 if (!s.isWritable())
2930 docstring const file = makeDisplayPath(s.absFilename(), 20);
2931 // Here we probably should run
2932 if (LyXVC::file_not_found_hook(s)) {
2933 docstring const text =
2934 bformat(_("Do you want to retrieve the document"
2935 " %1$s from version control?"), file);
2936 int const ret = Alert::prompt(_("Retrieve from version control?"),
2937 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2940 // How can we know _how_ to do the checkout?
2941 // With the current VC support it has to be,
2942 // a RCS file since CVS do not have special ,v files.
2944 return loadLyXFile(s);
2952 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2954 TeXErrors::Errors::const_iterator cit = terr.begin();
2955 TeXErrors::Errors::const_iterator end = terr.end();
2957 for (; cit != end; ++cit) {
2960 int errorRow = cit->error_in_line;
2961 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2967 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2968 } while (found && id_start == id_end && pos_start == pos_end);
2970 errorList.push_back(ErrorItem(cit->error_desc,
2971 cit->error_text, id_start, pos_start, pos_end));
2976 void Buffer::setBuffersForInsets() const
2978 inset().setBuffer(const_cast<Buffer &>(*this));
2982 void Buffer::updateLabels(UpdateScope scope) const
2984 // Use the master text class also for child documents
2985 Buffer const * const master = masterBuffer();
2986 DocumentClass const & textclass = master->params().documentClass();
2988 // keep the buffers to be children in this set. If the call from the
2989 // master comes back we can see which of them were actually seen (i.e.
2990 // via an InsetInclude). The remaining ones in the set need still be updated.
2991 static std::set<Buffer const *> bufToUpdate;
2992 if (scope == UpdateMaster) {
2993 // If this is a child document start with the master
2994 if (master != this) {
2995 bufToUpdate.insert(this);
2996 master->updateLabels();
2997 // Do this here in case the master has no gui associated with it. Then,
2998 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3002 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3003 if (bufToUpdate.find(this) == bufToUpdate.end())
3007 // start over the counters in the master
3008 textclass.counters().reset();
3011 // update will be done below for this buffer
3012 bufToUpdate.erase(this);
3014 // update all caches
3015 clearReferenceCache();
3018 Buffer & cbuf = const_cast<Buffer &>(*this);
3020 LASSERT(!text().paragraphs().empty(), /**/);
3023 ParIterator parit = cbuf.par_iterator_begin();
3024 updateLabels(parit);
3027 // TocBackend update will be done later.
3030 cbuf.tocBackend().update();
3031 if (scope == UpdateMaster)
3032 cbuf.structureChanged();
3036 static depth_type getDepth(DocIterator const & it)
3038 depth_type depth = 0;
3039 for (size_t i = 0 ; i < it.depth() ; ++i)
3040 if (!it[i].inset().inMathed())
3041 depth += it[i].paragraph().getDepth() + 1;
3042 // remove 1 since the outer inset does not count
3046 static depth_type getItemDepth(ParIterator const & it)
3048 Paragraph const & par = *it;
3049 LabelType const labeltype = par.layout().labeltype;
3051 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3054 // this will hold the lowest depth encountered up to now.
3055 depth_type min_depth = getDepth(it);
3056 ParIterator prev_it = it;
3059 --prev_it.top().pit();
3061 // start of nested inset: go to outer par
3063 if (prev_it.empty()) {
3064 // start of document: nothing to do
3069 // We search for the first paragraph with same label
3070 // that is not more deeply nested.
3071 Paragraph & prev_par = *prev_it;
3072 depth_type const prev_depth = getDepth(prev_it);
3073 if (labeltype == prev_par.layout().labeltype) {
3074 if (prev_depth < min_depth)
3075 return prev_par.itemdepth + 1;
3076 if (prev_depth == min_depth)
3077 return prev_par.itemdepth;
3079 min_depth = min(min_depth, prev_depth);
3080 // small optimization: if we are at depth 0, we won't
3081 // find anything else
3082 if (prev_depth == 0)
3088 static bool needEnumCounterReset(ParIterator const & it)
3090 Paragraph const & par = *it;
3091 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3092 depth_type const cur_depth = par.getDepth();
3093 ParIterator prev_it = it;
3094 while (prev_it.pit()) {
3095 --prev_it.top().pit();
3096 Paragraph const & prev_par = *prev_it;
3097 if (prev_par.getDepth() <= cur_depth)
3098 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3100 // start of nested inset: reset
3105 // set the label of a paragraph. This includes the counters.
3106 static void setLabel(Buffer const & buf, ParIterator & it)
3108 BufferParams const & bp = buf.masterBuffer()->params();
3109 DocumentClass const & textclass = bp.documentClass();
3110 Paragraph & par = it.paragraph();
3111 Layout const & layout = par.layout();
3112 Counters & counters = textclass.counters();
3114 if (par.params().startOfAppendix()) {
3115 // FIXME: only the counter corresponding to toplevel
3116 // sectionning should be reset
3118 counters.appendix(true);
3120 par.params().appendix(counters.appendix());
3122 // Compute the item depth of the paragraph
3123 par.itemdepth = getItemDepth(it);
3125 if (layout.margintype == MARGIN_MANUAL) {
3126 if (par.params().labelWidthString().empty())
3127 par.params().labelWidthString(par.translateIfPossible(layout.labelstring(), bp));
3129 par.params().labelWidthString(docstring());
3132 switch(layout.labeltype) {
3134 if (layout.toclevel <= bp.secnumdepth
3135 && (layout.latextype != LATEX_ENVIRONMENT
3136 || isFirstInSequence(it.pit(), it.plist()))) {
3137 counters.step(layout.counter);
3138 par.params().labelString(
3139 par.expandLabel(layout, bp));
3141 par.params().labelString(docstring());
3144 case LABEL_ITEMIZE: {
3145 // At some point of time we should do something more
3146 // clever here, like:
3147 // par.params().labelString(
3148 // bp.user_defined_bullet(par.itemdepth).getText());
3149 // for now, use a simple hardcoded label
3150 docstring itemlabel;
3151 switch (par.itemdepth) {
3153 itemlabel = char_type(0x2022);
3156 itemlabel = char_type(0x2013);
3159 itemlabel = char_type(0x2217);
3162 itemlabel = char_type(0x2219); // or 0x00b7
3165 par.params().labelString(itemlabel);
3169 case LABEL_ENUMERATE: {
3170 // FIXME: Yes I know this is a really, really! bad solution
3172 docstring enumcounter = from_ascii("enum");
3174 switch (par.itemdepth) {
3183 enumcounter += "iv";
3186 // not a valid enumdepth...
3190 // Maybe we have to reset the enumeration counter.
3191 if (needEnumCounterReset(it))
3192 counters.reset(enumcounter);
3194 counters.step(enumcounter);
3198 switch (par.itemdepth) {
3200 format = N_("\\arabic{enumi}.");
3203 format = N_("(\\alph{enumii})");
3206 format = N_("\\roman{enumiii}.");
3209 format = N_("\\Alph{enumiv}.");
3212 // not a valid enumdepth...
3216 par.params().labelString(counters.counterLabel(
3217 par.translateIfPossible(from_ascii(format), bp)));
3222 case LABEL_SENSITIVE: {
3223 string const & type = counters.current_float();
3224 docstring full_label;
3226 full_label = buf.B_("Senseless!!! ");
3228 docstring name = buf.B_(textclass.floats().getType(type).name());
3229 if (counters.hasCounter(from_utf8(type))) {
3230 counters.step(from_utf8(type));
3231 full_label = bformat(from_ascii("%1$s %2$s:"),
3233 counters.theCounter(from_utf8(type)));
3235 full_label = bformat(from_ascii("%1$s #:"), name);
3237 par.params().labelString(full_label);
3241 case LABEL_NO_LABEL:
3242 par.params().labelString(docstring());
3246 case LABEL_TOP_ENVIRONMENT:
3247 case LABEL_CENTERED_TOP_ENVIRONMENT:
3250 par.params().labelString(
3251 par.translateIfPossible(layout.labelstring(), bp));
3257 void Buffer::updateLabels(ParIterator & parit) const
3259 LASSERT(parit.pit() == 0, /**/);
3261 // set the position of the text in the buffer to be able
3262 // to resolve macros in it. This has nothing to do with
3263 // labels, but by putting it here we avoid implementing
3264 // a whole bunch of traversal routines just for this call.
3265 parit.text()->setMacrocontextPosition(parit);
3267 depth_type maxdepth = 0;
3268 pit_type const lastpit = parit.lastpit();
3269 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3270 // reduce depth if necessary
3271 parit->params().depth(min(parit->params().depth(), maxdepth));
3272 maxdepth = parit->getMaxDepthAfter();
3274 // set the counter for this paragraph
3275 setLabel(*this, parit);
3278 InsetList::const_iterator iit = parit->insetList().begin();
3279 InsetList::const_iterator end = parit->insetList().end();
3280 for (; iit != end; ++iit) {
3281 parit.pos() = iit->pos;
3282 iit->inset->updateLabels(parit);
3288 bool Buffer::nextWord(DocIterator & from, DocIterator & to,
3289 docstring & word) const
3291 bool inword = false;
3292 bool ignoreword = false;
3294 // Go backward a bit if needed in order to return the word currently
3295 // pointed by 'from'.
3296 while (from && from.pos() && isLetter(from))
3298 // OK, we start from here.
3300 while (to.depth()) {
3307 lang_code = to.paragraph().getFontSettings(params(),
3308 to.pos()).language()->code();
3310 // Insets like optional hyphens and ligature
3311 // break are part of a word.
3312 if (!to.paragraph().isInset(to.pos())) {
3313 char_type const c = to.paragraph().getChar(to.pos());
3318 } else { // !isLetter(cur)
3319 if (inword && !word.empty() && !ignoreword)
3331 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3332 WordLangTuple & word_lang, docstring_list & suggestions) const
3335 SpellChecker::Result res = SpellChecker::OK;
3336 SpellChecker * speller = theSpellChecker();
3337 suggestions.clear();
3339 while (nextWord(from, to, word)) {
3341 string lang_code = lyxrc.spellchecker_use_alt_lang
3342 ? lyxrc.spellchecker_alt_lang
3343 : from.paragraph().getFontSettings(params(), from.pos()).language()->code();
3344 WordLangTuple wl(word, lang_code);
3345 res = speller->check(wl);
3346 // ... just bail out if the spellchecker reports an error.
3347 if (!speller->error().empty()) {
3348 throw ExceptionMessage(WarningException,
3349 _("The spellchecker has failed."), speller->error());
3351 if (res != SpellChecker::OK && res != SpellChecker::IGNORED_WORD) {
3357 while (!(word = speller->nextMiss()).empty())
3358 suggestions.push_back(word);