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 "IndicesList.h"
36 #include "InsetIterator.h"
37 #include "InsetList.h"
39 #include "LaTeXFeatures.h"
43 #include "LyXAction.h"
47 #include "output_docbook.h"
49 #include "output_latex.h"
50 #include "output_plaintext.h"
51 #include "paragraph_funcs.h"
52 #include "Paragraph.h"
53 #include "ParagraphParameters.h"
54 #include "ParIterator.h"
55 #include "PDFOptions.h"
56 #include "SpellChecker.h"
59 #include "TexStream.h"
61 #include "TextClass.h"
62 #include "TocBackend.h"
64 #include "VCBackend.h"
66 #include "WordLangTuple.h"
69 #include "insets/InsetBibitem.h"
70 #include "insets/InsetBibtex.h"
71 #include "insets/InsetInclude.h"
72 #include "insets/InsetText.h"
74 #include "mathed/MacroTable.h"
75 #include "mathed/MathMacroTemplate.h"
76 #include "mathed/MathSupport.h"
78 #include "frontends/alert.h"
79 #include "frontends/Delegates.h"
80 #include "frontends/WorkAreaManager.h"
82 #include "graphics/Previews.h"
84 #include "support/lassert.h"
85 #include "support/convert.h"
86 #include "support/debug.h"
87 #include "support/docstring_list.h"
88 #include "support/ExceptionMessage.h"
89 #include "support/FileName.h"
90 #include "support/FileNameList.h"
91 #include "support/filetools.h"
92 #include "support/ForkedCalls.h"
93 #include "support/gettext.h"
94 #include "support/gzstream.h"
95 #include "support/lstrings.h"
96 #include "support/lyxalgo.h"
97 #include "support/os.h"
98 #include "support/Package.h"
99 #include "support/Path.h"
100 #include "support/Systemcall.h"
101 #include "support/textutils.h"
102 #include "support/types.h"
104 #include <boost/bind.hpp>
105 #include <boost/shared_ptr.hpp>
117 using namespace lyx::support;
121 namespace Alert = frontend::Alert;
122 namespace os = support::os;
126 // Do not remove the comment below, so we get merge conflict in
127 // independent branches. Instead add your own.
128 int const LYX_FORMAT = 361; // jspitzm: bibliography custom width
130 typedef map<string, bool> DepClean;
131 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
133 void showPrintError(string const & name)
135 docstring str = bformat(_("Could not print the document %1$s.\n"
136 "Check that your printer is set up correctly."),
137 makeDisplayPath(name, 50));
138 Alert::error(_("Print document failed"), str);
143 class BufferSet : public std::set<Buffer const *> {};
148 Impl(Buffer & parent, FileName const & file, bool readonly);
162 mutable TexRow texrow;
164 /// need to regenerate .tex?
168 mutable bool lyx_clean;
170 /// is autosave needed?
171 mutable bool bak_clean;
173 /// is this a unnamed file (New...)?
179 /// name of the file the buffer is associated with.
182 /** Set to true only when the file is fully loaded.
183 * Used to prevent the premature generation of previews
184 * and by the citation inset.
186 bool file_fully_loaded;
189 mutable TocBackend toc_backend;
192 typedef pair<DocIterator, MacroData> ScopeMacro;
193 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
194 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
195 /// map from the macro name to the position map,
196 /// which maps the macro definition position to the scope and the MacroData.
197 NamePositionScopeMacroMap macros;
200 /// positions of child buffers in the buffer
201 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
202 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
203 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
204 /// position of children buffers in this buffer
205 BufferPositionMap children_positions;
206 /// map from children inclusion positions to their scope and their buffer
207 PositionScopeBufferMap position_to_children;
209 /// Container for all sort of Buffer dependant errors.
210 map<string, ErrorList> errorLists;
212 /// timestamp and checksum used to test if the file has been externally
213 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
215 unsigned long checksum_;
218 frontend::WorkAreaManager * wa_;
223 /// A cache for the bibfiles (including bibfiles of loaded child
224 /// documents), needed for appropriate update of natbib labels.
225 mutable support::FileNameList bibfilesCache_;
227 // FIXME The caching mechanism could be improved. At present, we have a
228 // cache for each Buffer, that caches all the bibliography info for that
229 // Buffer. A more efficient solution would be to have a global cache per
230 // file, and then to construct the Buffer's bibinfo from that.
231 /// A cache for bibliography info
232 mutable BiblioInfo bibinfo_;
233 /// whether the bibinfo cache is valid
234 bool bibinfoCacheValid_;
235 /// Cache of timestamps of .bib files
236 map<FileName, time_t> bibfileStatus_;
238 mutable RefCache ref_cache_;
240 /// our Text that should be wrapped in an InsetText
243 /// This is here to force the test to be done whenever parent_buffer
245 Buffer const * parent() const {
246 // if parent_buffer is not loaded, then it has been unloaded,
247 // which means that parent_buffer is an invalid pointer. So we
248 // set it to null in that case.
249 if (!theBufferList().isLoaded(parent_buffer))
251 return parent_buffer;
254 void setParent(Buffer const * pb) { parent_buffer = pb; }
256 /// So we can force access via the accessors.
257 mutable Buffer const * parent_buffer;
261 /// Creates the per buffer temporary directory
262 static FileName createBufferTmpDir()
265 // We are in our own directory. Why bother to mangle name?
266 // In fact I wrote this code to circumvent a problematic behaviour
267 // (bug?) of EMX mkstemp().
268 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
269 convert<string>(count++));
271 if (!tmpfl.createDirectory(0777)) {
272 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
273 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
274 from_utf8(tmpfl.absFilename())));
280 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
281 : lyx_clean(true), bak_clean(true), unnamed(false),
282 read_only(readonly_), filename(file), file_fully_loaded(false),
283 toc_backend(&parent), macro_lock(false), timestamp_(0),
284 checksum_(0), wa_(0), undo_(parent), bibinfoCacheValid_(false),
287 temppath = createBufferTmpDir();
288 lyxvc.setBuffer(&parent);
290 wa_ = new frontend::WorkAreaManager;
294 Buffer::Buffer(string const & file, bool readonly)
295 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
297 LYXERR(Debug::INFO, "Buffer::Buffer()");
299 d->inset = new InsetText(*this);
300 d->inset->setAutoBreakRows(true);
301 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
307 LYXERR(Debug::INFO, "Buffer::~Buffer()");
308 // here the buffer should take care that it is
309 // saved properly, before it goes into the void.
311 // GuiView already destroyed
314 if (d->unnamed && d->filename.extension() == "internal") {
315 // No need to do additional cleanups for internal buffer.
320 // loop over children
321 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
322 Impl::BufferPositionMap::iterator end = d->children_positions.end();
323 for (; it != end; ++it) {
324 Buffer * child = const_cast<Buffer *>(it->first);
325 // The child buffer might have been closed already.
326 if (theBufferList().isLoaded(child))
327 theBufferList().releaseChild(this, child);
330 // clear references to children in macro tables
331 d->children_positions.clear();
332 d->position_to_children.clear();
334 if (!d->temppath.destroyDirectory()) {
335 Alert::warning(_("Could not remove temporary directory"),
336 bformat(_("Could not remove the temporary directory %1$s"),
337 from_utf8(d->temppath.absFilename())));
340 // Remove any previewed LaTeX snippets associated with this buffer.
341 thePreviews().removeLoader(*this);
347 void Buffer::changed() const
354 frontend::WorkAreaManager & Buffer::workAreaManager() const
356 LASSERT(d->wa_, /**/);
361 Text & Buffer::text() const
363 return d->inset->text();
367 Inset & Buffer::inset() const
373 BufferParams & Buffer::params()
379 BufferParams const & Buffer::params() const
385 ParagraphList & Buffer::paragraphs()
387 return text().paragraphs();
391 ParagraphList const & Buffer::paragraphs() const
393 return text().paragraphs();
397 LyXVC & Buffer::lyxvc()
403 LyXVC const & Buffer::lyxvc() const
409 string const Buffer::temppath() const
411 return d->temppath.absFilename();
415 TexRow & Buffer::texrow()
421 TexRow const & Buffer::texrow() const
427 TocBackend & Buffer::tocBackend() const
429 return d->toc_backend;
433 Undo & Buffer::undo()
439 string Buffer::latexName(bool const no_path) const
441 FileName latex_name = makeLatexName(d->filename);
442 return no_path ? latex_name.onlyFileName()
443 : latex_name.absFilename();
447 string Buffer::logName(LogType * type) const
449 string const filename = latexName(false);
451 if (filename.empty()) {
457 string const path = temppath();
459 FileName const fname(addName(temppath(),
460 onlyFilename(changeExtension(filename,
463 // FIXME: how do we know this is the name of the build log?
464 FileName const bname(
465 addName(path, onlyFilename(
466 changeExtension(filename,
467 formats.extension(bufferFormat()) + ".out"))));
469 // If no Latex log or Build log is newer, show Build log
471 if (bname.exists() &&
472 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
473 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
476 return bname.absFilename();
478 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
481 return fname.absFilename();
485 void Buffer::setReadonly(bool const flag)
487 if (d->read_only != flag) {
494 void Buffer::setFileName(string const & newfile)
496 d->filename = makeAbsPath(newfile);
497 setReadonly(d->filename.isReadOnly());
502 int Buffer::readHeader(Lexer & lex)
504 int unknown_tokens = 0;
506 int begin_header_line = -1;
508 // Initialize parameters that may be/go lacking in header:
509 params().branchlist().clear();
510 params().preamble.erase();
511 params().options.erase();
512 params().master.erase();
513 params().float_placement.erase();
514 params().paperwidth.erase();
515 params().paperheight.erase();
516 params().leftmargin.erase();
517 params().rightmargin.erase();
518 params().topmargin.erase();
519 params().bottommargin.erase();
520 params().headheight.erase();
521 params().headsep.erase();
522 params().footskip.erase();
523 params().columnsep.erase();
524 params().fontsCJK.erase();
525 params().listings_params.clear();
526 params().clearLayoutModules();
527 params().clearRemovedModules();
528 params().pdfoptions().clear();
529 params().indiceslist().clear();
530 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
532 for (int i = 0; i < 4; ++i) {
533 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
534 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
537 ErrorList & errorList = d->errorLists["Parse"];
546 if (token == "\\end_header")
550 if (token == "\\begin_header") {
551 begin_header_line = line;
555 LYXERR(Debug::PARSER, "Handling document header token: `"
558 string unknown = params().readToken(lex, token, d->filename.onlyPath());
559 if (!unknown.empty()) {
560 if (unknown[0] != '\\' && token == "\\textclass") {
561 Alert::warning(_("Unknown document class"),
562 bformat(_("Using the default document class, because the "
563 "class %1$s is unknown."), from_utf8(unknown)));
566 docstring const s = bformat(_("Unknown token: "
570 errorList.push_back(ErrorItem(_("Document header error"),
575 if (begin_header_line) {
576 docstring const s = _("\\begin_header is missing");
577 errorList.push_back(ErrorItem(_("Document header error"),
581 params().makeDocumentClass();
583 return unknown_tokens;
588 // changed to be public and have one parameter
589 // Returns true if "\end_document" is not read (Asger)
590 bool Buffer::readDocument(Lexer & lex)
592 ErrorList & errorList = d->errorLists["Parse"];
595 if (!lex.checkFor("\\begin_document")) {
596 docstring const s = _("\\begin_document is missing");
597 errorList.push_back(ErrorItem(_("Document header error"),
601 // we are reading in a brand new document
602 LASSERT(paragraphs().empty(), /**/);
606 if (params().outputChanges) {
607 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
608 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
609 LaTeXFeatures::isAvailable("xcolor");
611 if (!dvipost && !xcolorulem) {
612 Alert::warning(_("Changes not shown in LaTeX output"),
613 _("Changes will not be highlighted in LaTeX output, "
614 "because neither dvipost nor xcolor/ulem are installed.\n"
615 "Please install these packages or redefine "
616 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
617 } else if (!xcolorulem) {
618 Alert::warning(_("Changes not shown in LaTeX output"),
619 _("Changes will not be highlighted in LaTeX output "
620 "when using pdflatex, because xcolor and ulem are not installed.\n"
621 "Please install both packages or redefine "
622 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
626 if (!params().master.empty()) {
627 FileName const master_file = makeAbsPath(params().master,
628 onlyPath(absFileName()));
629 if (isLyXFilename(master_file.absFilename())) {
631 checkAndLoadLyXFile(master_file, true);
633 // necessary e.g. after a reload
634 // to re-register the child (bug 5873)
635 // FIXME: clean up updateMacros (here, only
636 // child registering is needed).
637 master->updateMacros();
638 // set master as master buffer, but only
639 // if we are a real child
640 if (master->isChild(this))
642 // if the master is not fully loaded
643 // it is probably just loading this
644 // child. No warning needed then.
645 else if (master->isFullyLoaded())
646 LYXERR0("The master '"
648 << "' assigned to this document ("
650 << ") does not include "
651 "this document. Ignoring the master assignment.");
657 bool const res = text().read(*this, lex, errorList, d->inset);
660 updateMacroInstances();
665 // needed to insert the selection
666 void Buffer::insertStringAsLines(ParagraphList & pars,
667 pit_type & pit, pos_type & pos,
668 Font const & fn, docstring const & str, bool autobreakrows)
672 // insert the string, don't insert doublespace
673 bool space_inserted = true;
674 for (docstring::const_iterator cit = str.begin();
675 cit != str.end(); ++cit) {
676 Paragraph & par = pars[pit];
678 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
679 breakParagraph(params(), pars, pit, pos,
680 par.layout().isEnvironment());
683 space_inserted = true;
687 // do not insert consecutive spaces if !free_spacing
688 } else if ((*cit == ' ' || *cit == '\t') &&
689 space_inserted && !par.isFreeSpacing()) {
691 } else if (*cit == '\t') {
692 if (!par.isFreeSpacing()) {
693 // tabs are like spaces here
694 par.insertChar(pos, ' ', font, params().trackChanges);
696 space_inserted = true;
698 par.insertChar(pos, *cit, font, params().trackChanges);
700 space_inserted = true;
702 } else if (!isPrintable(*cit)) {
703 // Ignore unprintables
706 // just insert the character
707 par.insertChar(pos, *cit, font, params().trackChanges);
709 space_inserted = (*cit == ' ');
716 bool Buffer::readString(string const & s)
718 params().compressed = false;
720 // remove dummy empty par
721 paragraphs().clear();
725 FileName const name = FileName::tempName("Buffer_readString");
726 switch (readFile(lex, name, true)) {
730 // We need to call lyx2lyx, so write the input to a file
731 ofstream os(name.toFilesystemEncoding().c_str());
734 return readFile(name);
744 bool Buffer::readFile(FileName const & filename)
746 FileName fname(filename);
748 params().compressed = fname.isZippedFile();
750 // remove dummy empty par
751 paragraphs().clear();
754 if (readFile(lex, fname) != success)
761 bool Buffer::isFullyLoaded() const
763 return d->file_fully_loaded;
767 void Buffer::setFullyLoaded(bool value)
769 d->file_fully_loaded = value;
773 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
776 LASSERT(!filename.empty(), /**/);
778 // the first (non-comment) token _must_ be...
779 if (!lex.checkFor("\\lyxformat")) {
780 Alert::error(_("Document format failure"),
781 bformat(_("%1$s is not a readable LyX document."),
782 from_utf8(filename.absFilename())));
788 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
789 // if present remove ".," from string.
790 size_t dot = tmp_format.find_first_of(".,");
791 //lyxerr << " dot found at " << dot << endl;
792 if (dot != string::npos)
793 tmp_format.erase(dot, 1);
794 int const file_format = convert<int>(tmp_format);
795 //lyxerr << "format: " << file_format << endl;
797 // save timestamp and checksum of the original disk file, making sure
798 // to not overwrite them with those of the file created in the tempdir
799 // when it has to be converted to the current format.
801 // Save the timestamp and checksum of disk file. If filename is an
802 // emergency file, save the timestamp and checksum of the original lyx file
803 // because isExternallyModified will check for this file. (BUG4193)
804 string diskfile = filename.absFilename();
805 if (suffixIs(diskfile, ".emergency"))
806 diskfile = diskfile.substr(0, diskfile.size() - 10);
807 saveCheckSum(FileName(diskfile));
810 if (file_format != LYX_FORMAT) {
813 // lyx2lyx would fail
816 FileName const tmpfile = FileName::tempName("Buffer_readFile");
817 if (tmpfile.empty()) {
818 Alert::error(_("Conversion failed"),
819 bformat(_("%1$s is from a different"
820 " version of LyX, but a temporary"
821 " file for converting it could"
823 from_utf8(filename.absFilename())));
826 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
827 if (lyx2lyx.empty()) {
828 Alert::error(_("Conversion script not found"),
829 bformat(_("%1$s is from a different"
830 " version of LyX, but the"
831 " conversion script lyx2lyx"
832 " could not be found."),
833 from_utf8(filename.absFilename())));
836 ostringstream command;
837 command << os::python()
838 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
839 << " -t " << convert<string>(LYX_FORMAT)
840 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
841 << ' ' << quoteName(filename.toFilesystemEncoding());
842 string const command_str = command.str();
844 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
846 cmd_ret const ret = runCommand(command_str);
847 if (ret.first != 0) {
848 Alert::error(_("Conversion script failed"),
849 bformat(_("%1$s is from a different version"
850 " of LyX, but the lyx2lyx script"
851 " failed to convert it."),
852 from_utf8(filename.absFilename())));
855 bool const ret = readFile(tmpfile);
856 // Do stuff with tmpfile name and buffer name here.
857 return ret ? success : failure;
862 if (readDocument(lex)) {
863 Alert::error(_("Document format failure"),
864 bformat(_("%1$s ended unexpectedly, which means"
865 " that it is probably corrupted."),
866 from_utf8(filename.absFilename())));
869 d->file_fully_loaded = true;
874 // Should probably be moved to somewhere else: BufferView? LyXView?
875 bool Buffer::save() const
877 // We don't need autosaves in the immediate future. (Asger)
878 resetAutosaveTimers();
880 string const encodedFilename = d->filename.toFilesystemEncoding();
883 bool madeBackup = false;
885 // make a backup if the file already exists
886 if (lyxrc.make_backup && fileName().exists()) {
887 backupName = FileName(absFileName() + '~');
888 if (!lyxrc.backupdir_path.empty()) {
889 string const mangledName =
890 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
891 backupName = FileName(addName(lyxrc.backupdir_path,
894 if (fileName().copyTo(backupName)) {
897 Alert::error(_("Backup failure"),
898 bformat(_("Cannot create backup file %1$s.\n"
899 "Please check whether the directory exists and is writeable."),
900 from_utf8(backupName.absFilename())));
901 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
905 // ask if the disk file has been externally modified (use checksum method)
906 if (fileName().exists() && isExternallyModified(checksum_method)) {
907 docstring const file = makeDisplayPath(absFileName(), 20);
908 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
909 "you want to overwrite this file?"), file);
910 int const ret = Alert::prompt(_("Overwrite modified file?"),
911 text, 1, 1, _("&Overwrite"), _("&Cancel"));
916 if (writeFile(d->filename)) {
920 // Saving failed, so backup is not backup
922 backupName.moveTo(d->filename);
928 bool Buffer::writeFile(FileName const & fname) const
930 if (d->read_only && fname == d->filename)
935 docstring const str = bformat(_("Saving document %1$s..."),
936 makeDisplayPath(fname.absFilename()));
939 if (params().compressed) {
940 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
941 retval = ofs && write(ofs);
943 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
944 retval = ofs && write(ofs);
948 message(str + _(" could not write file!"));
952 removeAutosaveFile();
954 saveCheckSum(d->filename);
955 message(str + _(" done."));
961 bool Buffer::write(ostream & ofs) const
964 // Use the standard "C" locale for file output.
965 ofs.imbue(locale::classic());
968 // The top of the file should not be written by params().
970 // write out a comment in the top of the file
971 ofs << "#LyX " << lyx_version
972 << " created this file. For more info see http://www.lyx.org/\n"
973 << "\\lyxformat " << LYX_FORMAT << "\n"
974 << "\\begin_document\n";
976 /// For each author, set 'used' to true if there is a change
977 /// by this author in the document; otherwise set it to 'false'.
978 AuthorList::Authors::const_iterator a_it = params().authors().begin();
979 AuthorList::Authors::const_iterator a_end = params().authors().end();
980 for (; a_it != a_end; ++a_it)
981 a_it->second.setUsed(false);
983 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
984 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
985 for ( ; it != end; ++it)
986 it->checkAuthors(params().authors());
988 // now write out the buffer parameters.
989 ofs << "\\begin_header\n";
990 params().writeFile(ofs);
991 ofs << "\\end_header\n";
994 ofs << "\n\\begin_body\n";
995 text().write(*this, ofs);
996 ofs << "\n\\end_body\n";
998 // Write marker that shows file is complete
999 ofs << "\\end_document" << endl;
1001 // Shouldn't really be needed....
1004 // how to check if close went ok?
1005 // Following is an attempt... (BE 20001011)
1007 // good() returns false if any error occured, including some
1008 // formatting error.
1009 // bad() returns true if something bad happened in the buffer,
1010 // which should include file system full errors.
1015 lyxerr << "File was not closed properly." << endl;
1022 bool Buffer::makeLaTeXFile(FileName const & fname,
1023 string const & original_path,
1024 OutputParams const & runparams_in,
1025 bool output_preamble, bool output_body) const
1027 OutputParams runparams = runparams_in;
1028 if (params().useXetex)
1029 runparams.flavor = OutputParams::XETEX;
1031 string const encoding = runparams.encoding->iconvName();
1032 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1035 try { ofs.reset(encoding); }
1036 catch (iconv_codecvt_facet_exception & e) {
1037 lyxerr << "Caught iconv exception: " << e.what() << endl;
1038 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1039 "verify that the support software for your encoding (%1$s) is "
1040 "properly installed"), from_ascii(encoding)));
1043 if (!openFileWrite(ofs, fname))
1046 //TexStream ts(ofs.rdbuf(), &texrow());
1047 ErrorList & errorList = d->errorLists["Export"];
1049 bool failed_export = false;
1052 writeLaTeXSource(ofs, original_path,
1053 runparams, output_preamble, output_body);
1055 catch (EncodingException & e) {
1056 odocstringstream ods;
1057 ods.put(e.failed_char);
1059 oss << "0x" << hex << e.failed_char << dec;
1060 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1061 " (code point %2$s)"),
1062 ods.str(), from_utf8(oss.str()));
1063 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1064 "representable in the chosen encoding.\n"
1065 "Changing the document encoding to utf8 could help."),
1066 e.par_id, e.pos, e.pos + 1));
1067 failed_export = true;
1069 catch (iconv_codecvt_facet_exception & e) {
1070 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1071 _(e.what()), -1, 0, 0));
1072 failed_export = true;
1074 catch (exception const & e) {
1075 errorList.push_back(ErrorItem(_("conversion failed"),
1076 _(e.what()), -1, 0, 0));
1077 failed_export = true;
1080 lyxerr << "Caught some really weird exception..." << endl;
1086 failed_export = true;
1087 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1091 return !failed_export;
1095 void Buffer::writeLaTeXSource(odocstream & os,
1096 string const & original_path,
1097 OutputParams const & runparams_in,
1098 bool const output_preamble, bool const output_body) const
1100 // The child documents, if any, shall be already loaded at this point.
1102 OutputParams runparams = runparams_in;
1104 // Classify the unicode characters appearing in math insets
1105 Encodings::initUnicodeMath(*this);
1107 // validate the buffer.
1108 LYXERR(Debug::LATEX, " Validating buffer...");
1109 LaTeXFeatures features(*this, params(), runparams);
1111 LYXERR(Debug::LATEX, " Buffer validation done.");
1113 // The starting paragraph of the coming rows is the
1114 // first paragraph of the document. (Asger)
1115 if (output_preamble && runparams.nice) {
1116 os << "%% LyX " << lyx_version << " created this file. "
1117 "For more info, see http://www.lyx.org/.\n"
1118 "%% Do not edit unless you really know what "
1120 d->texrow.newline();
1121 d->texrow.newline();
1123 LYXERR(Debug::INFO, "lyx document header finished");
1125 // Don't move this behind the parent_buffer=0 code below,
1126 // because then the macros will not get the right "redefinition"
1127 // flag as they don't see the parent macros which are output before.
1130 // fold macros if possible, still with parent buffer as the
1131 // macros will be put in the prefix anyway.
1132 updateMacroInstances();
1134 // There are a few differences between nice LaTeX and usual files:
1135 // usual is \batchmode and has a
1136 // special input@path to allow the including of figures
1137 // with either \input or \includegraphics (what figinsets do).
1138 // input@path is set when the actual parameter
1139 // original_path is set. This is done for usual tex-file, but not
1140 // for nice-latex-file. (Matthias 250696)
1141 // Note that input@path is only needed for something the user does
1142 // in the preamble, included .tex files or ERT, files included by
1143 // LyX work without it.
1144 if (output_preamble) {
1145 if (!runparams.nice) {
1146 // code for usual, NOT nice-latex-file
1147 os << "\\batchmode\n"; // changed
1148 // from \nonstopmode
1149 d->texrow.newline();
1151 if (!original_path.empty()) {
1153 // We don't know the encoding of inputpath
1154 docstring const inputpath = from_utf8(latex_path(original_path));
1155 os << "\\makeatletter\n"
1156 << "\\def\\input@path{{"
1157 << inputpath << "/}}\n"
1158 << "\\makeatother\n";
1159 d->texrow.newline();
1160 d->texrow.newline();
1161 d->texrow.newline();
1164 // get parent macros (if this buffer has a parent) which will be
1165 // written at the document begin further down.
1166 MacroSet parentMacros;
1167 listParentMacros(parentMacros, features);
1169 // Write the preamble
1170 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1172 runparams.use_japanese = features.isRequired("japanese");
1178 os << "\\begin{document}\n";
1179 d->texrow.newline();
1181 // output the parent macros
1182 MacroSet::iterator it = parentMacros.begin();
1183 MacroSet::iterator end = parentMacros.end();
1184 for (; it != end; ++it)
1185 (*it)->write(os, true);
1186 } // output_preamble
1188 d->texrow.start(paragraphs().begin()->id(), 0);
1190 LYXERR(Debug::INFO, "preamble finished, now the body.");
1192 // if we are doing a real file with body, even if this is the
1193 // child of some other buffer, let's cut the link here.
1194 // This happens for example if only a child document is printed.
1195 Buffer const * save_parent = 0;
1196 if (output_preamble) {
1197 save_parent = d->parent();
1202 latexParagraphs(*this, text(), os, d->texrow, runparams);
1204 // Restore the parenthood if needed
1205 if (output_preamble)
1206 d->setParent(save_parent);
1208 // add this just in case after all the paragraphs
1210 d->texrow.newline();
1212 if (output_preamble) {
1213 os << "\\end{document}\n";
1214 d->texrow.newline();
1215 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1217 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1219 runparams_in.encoding = runparams.encoding;
1221 // Just to be sure. (Asger)
1222 d->texrow.newline();
1224 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1225 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1229 bool Buffer::isLatex() const
1231 return params().documentClass().outputType() == LATEX;
1235 bool Buffer::isLiterate() const
1237 return params().documentClass().outputType() == LITERATE;
1241 bool Buffer::isDocBook() const
1243 return params().documentClass().outputType() == DOCBOOK;
1247 void Buffer::makeDocBookFile(FileName const & fname,
1248 OutputParams const & runparams,
1249 bool const body_only) const
1251 LYXERR(Debug::LATEX, "makeDocBookFile...");
1254 if (!openFileWrite(ofs, fname))
1257 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1261 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1265 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1266 OutputParams const & runparams,
1267 bool const only_body) const
1269 LaTeXFeatures features(*this, params(), runparams);
1274 DocumentClass const & tclass = params().documentClass();
1275 string const top_element = tclass.latexname();
1278 if (runparams.flavor == OutputParams::XML)
1279 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1282 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1285 if (! tclass.class_header().empty())
1286 os << from_ascii(tclass.class_header());
1287 else if (runparams.flavor == OutputParams::XML)
1288 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1289 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1291 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1293 docstring preamble = from_utf8(params().preamble);
1294 if (runparams.flavor != OutputParams::XML ) {
1295 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1296 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1297 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1298 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1301 string const name = runparams.nice
1302 ? changeExtension(absFileName(), ".sgml") : fname;
1303 preamble += features.getIncludedFiles(name);
1304 preamble += features.getLyXSGMLEntities();
1306 if (!preamble.empty()) {
1307 os << "\n [ " << preamble << " ]";
1312 string top = top_element;
1314 if (runparams.flavor == OutputParams::XML)
1315 top += params().language->code();
1317 top += params().language->code().substr(0, 2);
1320 if (!params().options.empty()) {
1322 top += params().options;
1325 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1326 << " file was created by LyX " << lyx_version
1327 << "\n See http://www.lyx.org/ for more information -->\n";
1329 params().documentClass().counters().reset();
1333 sgml::openTag(os, top);
1335 docbookParagraphs(paragraphs(), *this, os, runparams);
1336 sgml::closeTag(os, top_element);
1340 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1341 // Other flags: -wall -v0 -x
1342 int Buffer::runChktex()
1346 // get LaTeX-Filename
1347 FileName const path(temppath());
1348 string const name = addName(path.absFilename(), latexName());
1349 string const org_path = filePath();
1351 PathChanger p(path); // path to LaTeX file
1352 message(_("Running chktex..."));
1354 // Generate the LaTeX file if neccessary
1355 OutputParams runparams(¶ms().encoding());
1356 runparams.flavor = OutputParams::LATEX;
1357 runparams.nice = false;
1358 makeLaTeXFile(FileName(name), org_path, runparams);
1361 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1362 int const res = chktex.run(terr); // run chktex
1365 Alert::error(_("chktex failure"),
1366 _("Could not run chktex successfully."));
1367 } else if (res > 0) {
1368 ErrorList & errlist = d->errorLists["ChkTeX"];
1370 bufferErrors(terr, errlist);
1381 void Buffer::validate(LaTeXFeatures & features) const
1383 params().validate(features);
1387 for_each(paragraphs().begin(), paragraphs().end(),
1388 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1390 if (lyxerr.debugging(Debug::LATEX)) {
1391 features.showStruct();
1396 void Buffer::getLabelList(vector<docstring> & list) const
1398 // If this is a child document, use the parent's list instead.
1399 Buffer const * const pbuf = d->parent();
1401 pbuf->getLabelList(list);
1406 Toc & toc = d->toc_backend.toc("label");
1407 TocIterator toc_it = toc.begin();
1408 TocIterator end = toc.end();
1409 for (; toc_it != end; ++toc_it) {
1410 if (toc_it->depth() == 0)
1411 list.push_back(toc_it->str());
1416 void Buffer::updateBibfilesCache(UpdateScope scope) const
1418 // If this is a child document, use the parent's cache instead.
1419 Buffer const * const pbuf = d->parent();
1420 if (pbuf && scope != UpdateChildOnly) {
1421 pbuf->updateBibfilesCache();
1425 d->bibfilesCache_.clear();
1426 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1427 if (it->lyxCode() == BIBTEX_CODE) {
1428 InsetBibtex const & inset =
1429 static_cast<InsetBibtex const &>(*it);
1430 support::FileNameList const bibfiles = inset.getBibFiles();
1431 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1434 } else if (it->lyxCode() == INCLUDE_CODE) {
1435 InsetInclude & inset =
1436 static_cast<InsetInclude &>(*it);
1437 inset.updateBibfilesCache();
1438 support::FileNameList const & bibfiles =
1439 inset.getBibfilesCache();
1440 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1445 // the bibinfo cache is now invalid
1446 d->bibinfoCacheValid_ = false;
1450 void Buffer::invalidateBibinfoCache()
1452 d->bibinfoCacheValid_ = false;
1456 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1458 // If this is a child document, use the parent's cache instead.
1459 Buffer const * const pbuf = d->parent();
1460 if (pbuf && scope != UpdateChildOnly)
1461 return pbuf->getBibfilesCache();
1463 // We update the cache when first used instead of at loading time.
1464 if (d->bibfilesCache_.empty())
1465 const_cast<Buffer *>(this)->updateBibfilesCache(scope);
1467 return d->bibfilesCache_;
1471 BiblioInfo const & Buffer::masterBibInfo() const
1473 // if this is a child document and the parent is already loaded
1474 // use the parent's list instead [ale990412]
1475 Buffer const * const tmp = masterBuffer();
1478 return tmp->masterBibInfo();
1479 return localBibInfo();
1483 BiblioInfo const & Buffer::localBibInfo() const
1485 if (d->bibinfoCacheValid_) {
1486 support::FileNameList const & bibfilesCache = getBibfilesCache();
1487 // compare the cached timestamps with the actual ones.
1488 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1489 support::FileNameList::const_iterator en = bibfilesCache.end();
1490 for (; ei != en; ++ ei) {
1491 time_t lastw = ei->lastModified();
1492 if (lastw != d->bibfileStatus_[*ei]) {
1493 d->bibinfoCacheValid_ = false;
1494 d->bibfileStatus_[*ei] = lastw;
1500 if (!d->bibinfoCacheValid_) {
1501 d->bibinfo_.clear();
1502 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1503 it->fillWithBibKeys(d->bibinfo_, it);
1504 d->bibinfoCacheValid_ = true;
1510 bool Buffer::isDepClean(string const & name) const
1512 DepClean::const_iterator const it = d->dep_clean.find(name);
1513 if (it == d->dep_clean.end())
1519 void Buffer::markDepClean(string const & name)
1521 d->dep_clean[name] = true;
1525 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1527 switch (cmd.action) {
1528 case LFUN_BUFFER_EXPORT: {
1529 docstring const arg = cmd.argument();
1530 bool enable = arg == "custom" || isExportable(to_utf8(arg));
1532 flag.message(bformat(
1533 _("Don't know how to export to format: %1$s"), arg));
1534 flag.setEnabled(enable);
1538 case LFUN_BRANCH_ACTIVATE:
1539 case LFUN_BRANCH_DEACTIVATE: {
1540 BranchList const & branchList = params().branchlist();
1541 docstring const branchName = cmd.argument();
1542 flag.setEnabled(!branchName.empty()
1543 && branchList.find(branchName));
1547 case LFUN_BUFFER_PRINT:
1548 // if no Buffer is present, then of course we won't be called!
1549 flag.setEnabled(true);
1559 void Buffer::dispatch(string const & command, DispatchResult & result)
1561 return dispatch(lyxaction.lookupFunc(command), result);
1565 // NOTE We can end up here even if we have no GUI, because we are called
1566 // by LyX::exec to handled command-line requests. So we may need to check
1567 // whether we have a GUI or not. The boolean use_gui holds this information.
1568 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1570 // We'll set this back to false if need be.
1571 bool dispatched = true;
1573 switch (func.action) {
1574 case LFUN_BUFFER_EXPORT: {
1575 bool success = doExport(to_utf8(func.argument()), false);
1576 dr.setError(success);
1578 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
1583 case LFUN_BRANCH_ACTIVATE:
1584 case LFUN_BRANCH_DEACTIVATE: {
1585 BranchList & branchList = params().branchlist();
1586 docstring const branchName = func.argument();
1587 // the case without a branch name is handled elsewhere
1588 if (branchName.empty()) {
1592 Branch * branch = branchList.find(branchName);
1594 LYXERR0("Branch " << branchName << " does not exist.");
1596 docstring const msg =
1597 bformat(_("Branch \"%1$s\" does not exist."), branchName);
1600 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1602 dr.update(Update::Force);
1607 case LFUN_BUFFER_PRINT: {
1608 // we'll assume there's a problem until we succeed
1610 string target = func.getArg(0);
1611 string target_name = func.getArg(1);
1612 string command = func.getArg(2);
1615 || target_name.empty()
1616 || command.empty()) {
1617 LYXERR0("Unable to parse " << func.argument());
1618 docstring const msg =
1619 bformat(_("Unable to parse \"%1$s\""), func.argument());
1623 if (target != "printer" && target != "file") {
1624 LYXERR0("Unrecognized target \"" << target << '"');
1625 docstring const msg =
1626 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
1631 if (!doExport("dvi", true)) {
1632 showPrintError(absFileName());
1633 dr.setMessage(_("Error exporting to DVI."));
1637 // Push directory path.
1638 string const path = temppath();
1639 // Prevent the compiler from optimizing away p
1643 // there are three cases here:
1644 // 1. we print to a file
1645 // 2. we print directly to a printer
1646 // 3. we print using a spool command (print to file first)
1649 string const dviname = changeExtension(latexName(true), "dvi");
1651 if (target == "printer") {
1652 if (!lyxrc.print_spool_command.empty()) {
1653 // case 3: print using a spool
1654 string const psname = changeExtension(dviname,".ps");
1655 command += ' ' + lyxrc.print_to_file
1658 + quoteName(dviname);
1660 string command2 = lyxrc.print_spool_command + ' ';
1661 if (target_name != "default") {
1662 command2 += lyxrc.print_spool_printerprefix
1666 command2 += quoteName(psname);
1668 // If successful, then spool command
1669 res = one.startscript(Systemcall::Wait, command);
1672 // If there's no GUI, we have to wait on this command. Otherwise,
1673 // LyX deletes the temporary directory, and with it the spooled
1674 // file, before it can be printed!!
1675 Systemcall::Starttype stype = use_gui ?
1676 Systemcall::DontWait : Systemcall::Wait;
1677 res = one.startscript(stype, command2);
1680 // case 2: print directly to a printer
1681 if (target_name != "default")
1682 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
1684 Systemcall::Starttype stype = use_gui ?
1685 Systemcall::DontWait : Systemcall::Wait;
1686 res = one.startscript(stype, command + quoteName(dviname));
1690 // case 1: print to a file
1691 FileName const filename(makeAbsPath(target_name, filePath()));
1692 FileName const dvifile(makeAbsPath(dviname, path));
1693 if (filename.exists()) {
1694 docstring text = bformat(
1695 _("The file %1$s already exists.\n\n"
1696 "Do you want to overwrite that file?"),
1697 makeDisplayPath(filename.absFilename()));
1698 if (Alert::prompt(_("Overwrite file?"),
1699 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
1702 command += ' ' + lyxrc.print_to_file
1703 + quoteName(filename.toFilesystemEncoding())
1705 + quoteName(dvifile.toFilesystemEncoding());
1707 Systemcall::Starttype stype = use_gui ?
1708 Systemcall::DontWait : Systemcall::Wait;
1709 res = one.startscript(stype, command);
1715 dr.setMessage(_("Error running external commands."));
1716 showPrintError(absFileName());
1725 dr.dispatched(dispatched);
1729 void Buffer::changeLanguage(Language const * from, Language const * to)
1731 LASSERT(from, /**/);
1734 for_each(par_iterator_begin(),
1736 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1740 bool Buffer::isMultiLingual() const
1742 ParConstIterator end = par_iterator_end();
1743 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1744 if (it->isMultiLingual(params()))
1751 DocIterator Buffer::getParFromID(int const id) const
1753 Buffer * buf = const_cast<Buffer *>(this);
1755 // John says this is called with id == -1 from undo
1756 lyxerr << "getParFromID(), id: " << id << endl;
1757 return doc_iterator_end(buf);
1760 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
1761 if (it.paragraph().id() == id)
1764 return doc_iterator_end(buf);
1768 bool Buffer::hasParWithID(int const id) const
1770 return !getParFromID(id).atEnd();
1774 ParIterator Buffer::par_iterator_begin()
1776 return ParIterator(doc_iterator_begin(this));
1780 ParIterator Buffer::par_iterator_end()
1782 return ParIterator(doc_iterator_end(this));
1786 ParConstIterator Buffer::par_iterator_begin() const
1788 return ParConstIterator(doc_iterator_begin(this));
1792 ParConstIterator Buffer::par_iterator_end() const
1794 return ParConstIterator(doc_iterator_end(this));
1798 Language const * Buffer::language() const
1800 return params().language;
1804 docstring const Buffer::B_(string const & l10n) const
1806 return params().B_(l10n);
1810 bool Buffer::isClean() const
1812 return d->lyx_clean;
1816 bool Buffer::isBakClean() const
1818 return d->bak_clean;
1822 bool Buffer::isExternallyModified(CheckMethod method) const
1824 LASSERT(d->filename.exists(), /**/);
1825 // if method == timestamp, check timestamp before checksum
1826 return (method == checksum_method
1827 || d->timestamp_ != d->filename.lastModified())
1828 && d->checksum_ != d->filename.checksum();
1832 void Buffer::saveCheckSum(FileName const & file) const
1834 if (file.exists()) {
1835 d->timestamp_ = file.lastModified();
1836 d->checksum_ = file.checksum();
1838 // in the case of save to a new file.
1845 void Buffer::markClean() const
1847 if (!d->lyx_clean) {
1848 d->lyx_clean = true;
1851 // if the .lyx file has been saved, we don't need an
1853 d->bak_clean = true;
1857 void Buffer::markBakClean() const
1859 d->bak_clean = true;
1863 void Buffer::setUnnamed(bool flag)
1869 bool Buffer::isUnnamed() const
1875 // FIXME: this function should be moved to buffer_pimpl.C
1876 void Buffer::markDirty()
1879 d->lyx_clean = false;
1882 d->bak_clean = false;
1884 DepClean::iterator it = d->dep_clean.begin();
1885 DepClean::const_iterator const end = d->dep_clean.end();
1887 for (; it != end; ++it)
1892 FileName Buffer::fileName() const
1898 string Buffer::absFileName() const
1900 return d->filename.absFilename();
1904 string Buffer::filePath() const
1906 return d->filename.onlyPath().absFilename() + "/";
1910 bool Buffer::isReadonly() const
1912 return d->read_only;
1916 void Buffer::setParent(Buffer const * buffer)
1918 // Avoids recursive include.
1919 d->setParent(buffer == this ? 0 : buffer);
1924 Buffer const * Buffer::parent() const
1930 void Buffer::collectRelatives(BufferSet & bufs) const
1934 parent()->collectRelatives(bufs);
1936 // loop over children
1937 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1938 Impl::BufferPositionMap::iterator end = d->children_positions.end();
1939 for (; it != end; ++it)
1940 bufs.insert(const_cast<Buffer *>(it->first));
1944 std::vector<Buffer const *> Buffer::allRelatives() const
1947 collectRelatives(bufs);
1948 BufferSet::iterator it = bufs.begin();
1949 std::vector<Buffer const *> ret;
1950 for (; it != bufs.end(); ++it)
1956 Buffer const * Buffer::masterBuffer() const
1958 Buffer const * const pbuf = d->parent();
1962 return pbuf->masterBuffer();
1966 bool Buffer::isChild(Buffer * child) const
1968 return d->children_positions.find(child) != d->children_positions.end();
1972 DocIterator Buffer::firstChildPosition(Buffer const * child)
1974 Impl::BufferPositionMap::iterator it;
1975 it = d->children_positions.find(child);
1976 if (it == d->children_positions.end())
1977 return DocIterator(this);
1982 std::vector<Buffer *> Buffer::getChildren() const
1984 std::vector<Buffer *> clist;
1985 // loop over children
1986 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1987 Impl::BufferPositionMap::iterator end = d->children_positions.end();
1988 for (; it != end; ++it) {
1989 Buffer * child = const_cast<Buffer *>(it->first);
1990 clist.push_back(child);
1991 // there might be grandchildren
1992 std::vector<Buffer *> glist = child->getChildren();
1993 for (vector<Buffer *>::const_iterator git = glist.begin();
1994 git != glist.end(); ++git)
1995 clist.push_back(*git);
2001 template<typename M>
2002 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
2007 typename M::iterator it = m.lower_bound(x);
2008 if (it == m.begin())
2016 MacroData const * Buffer::getBufferMacro(docstring const & name,
2017 DocIterator const & pos) const
2019 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2021 // if paragraphs have no macro context set, pos will be empty
2025 // we haven't found anything yet
2026 DocIterator bestPos = par_iterator_begin();
2027 MacroData const * bestData = 0;
2029 // find macro definitions for name
2030 Impl::NamePositionScopeMacroMap::iterator nameIt
2031 = d->macros.find(name);
2032 if (nameIt != d->macros.end()) {
2033 // find last definition in front of pos or at pos itself
2034 Impl::PositionScopeMacroMap::const_iterator it
2035 = greatest_below(nameIt->second, pos);
2036 if (it != nameIt->second.end()) {
2038 // scope ends behind pos?
2039 if (pos < it->second.first) {
2040 // Looks good, remember this. If there
2041 // is no external macro behind this,
2042 // we found the right one already.
2043 bestPos = it->first;
2044 bestData = &it->second.second;
2048 // try previous macro if there is one
2049 if (it == nameIt->second.begin())
2056 // find macros in included files
2057 Impl::PositionScopeBufferMap::const_iterator it
2058 = greatest_below(d->position_to_children, pos);
2059 if (it == d->position_to_children.end())
2060 // no children before
2064 // do we know something better (i.e. later) already?
2065 if (it->first < bestPos )
2068 // scope ends behind pos?
2069 if (pos < it->second.first) {
2070 // look for macro in external file
2071 d->macro_lock = true;
2072 MacroData const * data
2073 = it->second.second->getMacro(name, false);
2074 d->macro_lock = false;
2076 bestPos = it->first;
2082 // try previous file if there is one
2083 if (it == d->position_to_children.begin())
2088 // return the best macro we have found
2093 MacroData const * Buffer::getMacro(docstring const & name,
2094 DocIterator const & pos, bool global) const
2099 // query buffer macros
2100 MacroData const * data = getBufferMacro(name, pos);
2104 // If there is a master buffer, query that
2105 Buffer const * const pbuf = d->parent();
2107 d->macro_lock = true;
2108 MacroData const * macro = pbuf->getMacro(
2109 name, *this, false);
2110 d->macro_lock = false;
2116 data = MacroTable::globalMacros().get(name);
2125 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2127 // set scope end behind the last paragraph
2128 DocIterator scope = par_iterator_begin();
2129 scope.pit() = scope.lastpit() + 1;
2131 return getMacro(name, scope, global);
2135 MacroData const * Buffer::getMacro(docstring const & name,
2136 Buffer const & child, bool global) const
2138 // look where the child buffer is included first
2139 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2140 if (it == d->children_positions.end())
2143 // check for macros at the inclusion position
2144 return getMacro(name, it->second, global);
2148 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
2150 pit_type lastpit = it.lastpit();
2152 // look for macros in each paragraph
2153 while (it.pit() <= lastpit) {
2154 Paragraph & par = it.paragraph();
2156 // iterate over the insets of the current paragraph
2157 InsetList const & insets = par.insetList();
2158 InsetList::const_iterator iit = insets.begin();
2159 InsetList::const_iterator end = insets.end();
2160 for (; iit != end; ++iit) {
2161 it.pos() = iit->pos;
2163 // is it a nested text inset?
2164 if (iit->inset->asInsetText()) {
2165 // Inset needs its own scope?
2166 InsetText const * itext = iit->inset->asInsetText();
2167 bool newScope = itext->isMacroScope();
2169 // scope which ends just behind the inset
2170 DocIterator insetScope = it;
2173 // collect macros in inset
2174 it.push_back(CursorSlice(*iit->inset));
2175 updateMacros(it, newScope ? insetScope : scope);
2180 // is it an external file?
2181 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2182 // get buffer of external file
2183 InsetInclude const & inset =
2184 static_cast<InsetInclude const &>(*iit->inset);
2185 d->macro_lock = true;
2186 Buffer * child = inset.getChildBuffer();
2187 d->macro_lock = false;
2191 // register its position, but only when it is
2192 // included first in the buffer
2193 if (d->children_positions.find(child) ==
2194 d->children_positions.end())
2195 d->children_positions[child] = it;
2197 // register child with its scope
2198 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
2202 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2206 MathMacroTemplate & macroTemplate =
2207 static_cast<MathMacroTemplate &>(*iit->inset);
2208 MacroContext mc(*this, it);
2209 macroTemplate.updateToContext(mc);
2212 bool valid = macroTemplate.validMacro();
2213 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2214 // then the BufferView's cursor will be invalid in
2215 // some cases which leads to crashes.
2220 d->macros[macroTemplate.name()][it] =
2221 Impl::ScopeMacro(scope, MacroData(*this, it));
2231 void Buffer::updateMacros() const
2236 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2238 // start with empty table
2240 d->children_positions.clear();
2241 d->position_to_children.clear();
2243 // Iterate over buffer, starting with first paragraph
2244 // The scope must be bigger than any lookup DocIterator
2245 // later. For the global lookup, lastpit+1 is used, hence
2246 // we use lastpit+2 here.
2247 DocIterator it = par_iterator_begin();
2248 DocIterator outerScope = it;
2249 outerScope.pit() = outerScope.lastpit() + 2;
2250 updateMacros(it, outerScope);
2254 void Buffer::updateMacroInstances() const
2256 LYXERR(Debug::MACROS, "updateMacroInstances for "
2257 << d->filename.onlyFileName());
2258 DocIterator it = doc_iterator_begin(this);
2259 DocIterator end = doc_iterator_end(this);
2260 for (; it != end; it.forwardPos()) {
2261 // look for MathData cells in InsetMathNest insets
2262 Inset * inset = it.nextInset();
2266 InsetMath * minset = inset->asInsetMath();
2270 // update macro in all cells of the InsetMathNest
2271 DocIterator::idx_type n = minset->nargs();
2272 MacroContext mc = MacroContext(*this, it);
2273 for (DocIterator::idx_type i = 0; i < n; ++i) {
2274 MathData & data = minset->cell(i);
2275 data.updateMacros(0, mc);
2281 void Buffer::listMacroNames(MacroNameSet & macros) const
2286 d->macro_lock = true;
2288 // loop over macro names
2289 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2290 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2291 for (; nameIt != nameEnd; ++nameIt)
2292 macros.insert(nameIt->first);
2294 // loop over children
2295 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2296 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2297 for (; it != end; ++it)
2298 it->first->listMacroNames(macros);
2301 Buffer const * const pbuf = d->parent();
2303 pbuf->listMacroNames(macros);
2305 d->macro_lock = false;
2309 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2311 Buffer const * const pbuf = d->parent();
2316 pbuf->listMacroNames(names);
2319 MacroNameSet::iterator it = names.begin();
2320 MacroNameSet::iterator end = names.end();
2321 for (; it != end; ++it) {
2323 MacroData const * data =
2324 pbuf->getMacro(*it, *this, false);
2326 macros.insert(data);
2328 // we cannot access the original MathMacroTemplate anymore
2329 // here to calls validate method. So we do its work here manually.
2330 // FIXME: somehow make the template accessible here.
2331 if (data->optionals() > 0)
2332 features.require("xargs");
2338 Buffer::References & Buffer::references(docstring const & label)
2341 return const_cast<Buffer *>(masterBuffer())->references(label);
2343 RefCache::iterator it = d->ref_cache_.find(label);
2344 if (it != d->ref_cache_.end())
2345 return it->second.second;
2347 static InsetLabel const * dummy_il = 0;
2348 static References const dummy_refs;
2349 it = d->ref_cache_.insert(
2350 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2351 return it->second.second;
2355 Buffer::References const & Buffer::references(docstring const & label) const
2357 return const_cast<Buffer *>(this)->references(label);
2361 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2363 masterBuffer()->d->ref_cache_[label].first = il;
2367 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2369 return masterBuffer()->d->ref_cache_[label].first;
2373 void Buffer::clearReferenceCache() const
2376 d->ref_cache_.clear();
2380 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2383 //FIXME: This does not work for child documents yet.
2384 LASSERT(code == CITE_CODE, /**/);
2385 // Check if the label 'from' appears more than once
2386 vector<docstring> labels;
2388 BiblioInfo const & keys = masterBibInfo();
2389 BiblioInfo::const_iterator bit = keys.begin();
2390 BiblioInfo::const_iterator bend = keys.end();
2392 for (; bit != bend; ++bit)
2394 labels.push_back(bit->first);
2397 if (count(labels.begin(), labels.end(), from) > 1)
2400 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2401 if (it->lyxCode() == code) {
2402 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2403 docstring const oldValue = inset.getParam(paramName);
2404 if (oldValue == from)
2405 inset.setParam(paramName, to);
2411 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2412 pit_type par_end, bool full_source) const
2414 OutputParams runparams(¶ms().encoding());
2415 runparams.nice = true;
2416 runparams.flavor = params().useXetex ?
2417 OutputParams::XETEX : OutputParams::LATEX;
2418 runparams.linelen = lyxrc.plaintext_linelen;
2419 // No side effect of file copying and image conversion
2420 runparams.dryrun = true;
2423 os << "% " << _("Preview source code") << "\n\n";
2425 d->texrow.newline();
2426 d->texrow.newline();
2428 writeDocBookSource(os, absFileName(), runparams, false);
2430 // latex or literate
2431 writeLaTeXSource(os, string(), runparams, true, true);
2433 runparams.par_begin = par_begin;
2434 runparams.par_end = par_end;
2435 if (par_begin + 1 == par_end) {
2437 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2441 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2442 convert<docstring>(par_begin),
2443 convert<docstring>(par_end - 1))
2450 // output paragraphs
2452 docbookParagraphs(paragraphs(), *this, os, runparams);
2454 // latex or literate
2455 latexParagraphs(*this, text(), os, texrow, runparams);
2460 ErrorList & Buffer::errorList(string const & type) const
2462 static ErrorList emptyErrorList;
2463 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2464 if (I == d->errorLists.end())
2465 return emptyErrorList;
2471 void Buffer::updateTocItem(std::string const & type,
2472 DocIterator const & dit) const
2475 gui_->updateTocItem(type, dit);
2479 void Buffer::structureChanged() const
2482 gui_->structureChanged();
2486 void Buffer::errors(string const & err) const
2493 void Buffer::message(docstring const & msg) const
2500 void Buffer::setBusy(bool on) const
2507 void Buffer::setReadOnly(bool on) const
2510 d->wa_->setReadOnly(on);
2514 void Buffer::updateTitles() const
2517 d->wa_->updateTitles();
2521 void Buffer::resetAutosaveTimers() const
2524 gui_->resetAutosaveTimers();
2528 bool Buffer::hasGuiDelegate() const
2534 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2543 class AutoSaveBuffer : public ForkedProcess {
2546 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2547 : buffer_(buffer), fname_(fname) {}
2549 virtual boost::shared_ptr<ForkedProcess> clone() const
2551 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2556 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2557 from_utf8(fname_.absFilename())));
2558 return run(DontWait);
2562 virtual int generateChild();
2564 Buffer const & buffer_;
2569 int AutoSaveBuffer::generateChild()
2571 // tmp_ret will be located (usually) in /tmp
2572 // will that be a problem?
2573 // Note that this calls ForkedCalls::fork(), so it's
2574 // ok cross-platform.
2575 pid_t const pid = fork();
2576 // If you want to debug the autosave
2577 // you should set pid to -1, and comment out the fork.
2578 if (pid != 0 && pid != -1)
2581 // pid = -1 signifies that lyx was unable
2582 // to fork. But we will do the save
2584 bool failed = false;
2585 FileName const tmp_ret = FileName::tempName("lyxauto");
2586 if (!tmp_ret.empty()) {
2587 buffer_.writeFile(tmp_ret);
2588 // assume successful write of tmp_ret
2589 if (!tmp_ret.moveTo(fname_))
2595 // failed to write/rename tmp_ret so try writing direct
2596 if (!buffer_.writeFile(fname_)) {
2597 // It is dangerous to do this in the child,
2598 // but safe in the parent, so...
2599 if (pid == -1) // emit message signal.
2600 buffer_.message(_("Autosave failed!"));
2604 if (pid == 0) // we are the child so...
2613 FileName Buffer::getAutosaveFilename() const
2615 // if the document is unnamed try to save in the backup dir, else
2616 // in the default document path, and as a last try in the filePath,
2617 // which will most often be the temporary directory
2620 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
2621 : lyxrc.backupdir_path;
2622 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
2625 string const fname = "#" + d->filename.onlyFileName() + "#";
2626 return makeAbsPath(fname, fpath);
2630 void Buffer::removeAutosaveFile() const
2632 FileName const f = getAutosaveFilename();
2638 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
2640 FileName const newauto = getAutosaveFilename();
2641 if (!(oldauto == newauto || oldauto.moveTo(newauto)))
2642 LYXERR0("Unable to remove autosave file `" << oldauto << "'!");
2646 // Perfect target for a thread...
2647 void Buffer::autoSave() const
2649 if (isBakClean() || isReadonly()) {
2650 // We don't save now, but we'll try again later
2651 resetAutosaveTimers();
2655 // emit message signal.
2656 message(_("Autosaving current document..."));
2657 AutoSaveBuffer autosave(*this, getAutosaveFilename());
2661 resetAutosaveTimers();
2665 string Buffer::bufferFormat() const
2667 string format = params().documentClass().outputFormat();
2668 if (format == "latex") {
2669 if (params().useXetex)
2671 if (params().encoding().package() == Encoding::japanese)
2678 string Buffer::getDefaultOutputFormat() const
2680 if (!params().defaultOutputFormat.empty()
2681 && params().defaultOutputFormat != "default")
2682 return params().defaultOutputFormat;
2683 typedef vector<Format const *> Formats;
2684 Formats formats = exportableFormats(true);
2687 || params().useXetex
2688 || params().encoding().package() == Encoding::japanese) {
2689 if (formats.empty())
2691 // return the first we find
2692 return formats.front()->name();
2694 return lyxrc.default_view_format;
2699 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2700 string & result_file) const
2702 string backend_format;
2703 OutputParams runparams(¶ms().encoding());
2704 runparams.flavor = OutputParams::LATEX;
2705 runparams.linelen = lyxrc.plaintext_linelen;
2706 vector<string> backs = backends();
2707 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2708 // Get shortest path to format
2709 Graph::EdgePath path;
2710 for (vector<string>::const_iterator it = backs.begin();
2711 it != backs.end(); ++it) {
2712 Graph::EdgePath p = theConverters().getPath(*it, format);
2713 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2714 backend_format = *it;
2719 runparams.flavor = theConverters().getFlavor(path);
2721 Alert::error(_("Couldn't export file"),
2722 bformat(_("No information for exporting the format %1$s."),
2723 formats.prettyName(format)));
2727 backend_format = format;
2728 // FIXME: Don't hardcode format names here, but use a flag
2729 if (backend_format == "pdflatex")
2730 runparams.flavor = OutputParams::PDFLATEX;
2733 string filename = latexName(false);
2734 filename = addName(temppath(), filename);
2735 filename = changeExtension(filename,
2736 formats.extension(backend_format));
2739 updateMacroInstances();
2741 // Plain text backend
2742 if (backend_format == "text")
2743 writePlaintextFile(*this, FileName(filename), runparams);
2745 else if (backend_format == "lyx")
2746 writeFile(FileName(filename));
2748 else if (isDocBook()) {
2749 runparams.nice = !put_in_tempdir;
2750 makeDocBookFile(FileName(filename), runparams);
2753 else if (backend_format == format) {
2754 runparams.nice = true;
2755 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2757 } else if (!lyxrc.tex_allows_spaces
2758 && contains(filePath(), ' ')) {
2759 Alert::error(_("File name error"),
2760 _("The directory path to the document cannot contain spaces."));
2763 runparams.nice = false;
2764 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2768 string const error_type = (format == "program")
2769 ? "Build" : bufferFormat();
2770 ErrorList & error_list = d->errorLists[error_type];
2771 string const ext = formats.extension(format);
2772 FileName const tmp_result_file(changeExtension(filename, ext));
2773 bool const success = theConverters().convert(this, FileName(filename),
2774 tmp_result_file, FileName(absFileName()), backend_format, format,
2776 // Emit the signal to show the error list.
2777 if (format != backend_format)
2782 if (put_in_tempdir) {
2783 result_file = tmp_result_file.absFilename();
2787 result_file = changeExtension(absFileName(), ext);
2788 // We need to copy referenced files (e. g. included graphics
2789 // if format == "dvi") to the result dir.
2790 vector<ExportedFile> const files =
2791 runparams.exportdata->externalFiles(format);
2792 string const dest = onlyPath(result_file);
2793 CopyStatus status = SUCCESS;
2794 for (vector<ExportedFile>::const_iterator it = files.begin();
2795 it != files.end() && status != CANCEL; ++it) {
2796 string const fmt = formats.getFormatFromFile(it->sourceName);
2797 status = copyFile(fmt, it->sourceName,
2798 makeAbsPath(it->exportName, dest),
2799 it->exportName, status == FORCE);
2801 if (status == CANCEL) {
2802 message(_("Document export cancelled."));
2803 } else if (tmp_result_file.exists()) {
2804 // Finally copy the main file
2805 status = copyFile(format, tmp_result_file,
2806 FileName(result_file), result_file,
2808 message(bformat(_("Document exported as %1$s "
2810 formats.prettyName(format),
2811 makeDisplayPath(result_file)));
2813 // This must be a dummy converter like fax (bug 1888)
2814 message(bformat(_("Document exported as %1$s"),
2815 formats.prettyName(format)));
2822 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2825 return doExport(format, put_in_tempdir, result_file);
2829 bool Buffer::preview(string const & format) const
2832 if (!doExport(format, true, result_file))
2834 return formats.view(*this, FileName(result_file), format);
2838 bool Buffer::isExportable(string const & format) const
2840 vector<string> backs = backends();
2841 for (vector<string>::const_iterator it = backs.begin();
2842 it != backs.end(); ++it)
2843 if (theConverters().isReachable(*it, format))
2849 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2851 vector<string> backs = backends();
2852 vector<Format const *> result =
2853 theConverters().getReachable(backs[0], only_viewable, true);
2854 for (vector<string>::const_iterator it = backs.begin() + 1;
2855 it != backs.end(); ++it) {
2856 vector<Format const *> r =
2857 theConverters().getReachable(*it, only_viewable, false);
2858 result.insert(result.end(), r.begin(), r.end());
2864 vector<string> Buffer::backends() const
2867 if (params().baseClass()->isTeXClassAvailable()) {
2868 v.push_back(bufferFormat());
2869 // FIXME: Don't hardcode format names here, but use a flag
2870 if (v.back() == "latex")
2871 v.push_back("pdflatex");
2873 v.push_back("text");
2879 bool Buffer::readFileHelper(FileName const & s)
2881 // File information about normal file
2883 docstring const file = makeDisplayPath(s.absFilename(), 50);
2884 docstring text = bformat(_("The specified document\n%1$s"
2885 "\ncould not be read."), file);
2886 Alert::error(_("Could not read document"), text);
2890 // Check if emergency save file exists and is newer.
2891 FileName const e(s.absFilename() + ".emergency");
2893 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2894 docstring const file = makeDisplayPath(s.absFilename(), 20);
2895 docstring const text =
2896 bformat(_("An emergency save of the document "
2898 "Recover emergency save?"), file);
2899 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2900 _("&Recover"), _("&Load Original"),
2904 // the file is not saved if we load the emergency file.
2914 // Now check if autosave file is newer.
2915 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2917 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2918 docstring const file = makeDisplayPath(s.absFilename(), 20);
2919 docstring const text =
2920 bformat(_("The backup of the document "
2921 "%1$s is newer.\n\nLoad the "
2922 "backup instead?"), file);
2923 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2924 _("&Load backup"), _("Load &original"),
2928 // the file is not saved if we load the autosave file.
2932 // Here we delete the autosave
2943 bool Buffer::loadLyXFile(FileName const & s)
2945 if (s.isReadableFile()) {
2946 if (readFileHelper(s)) {
2947 lyxvc().file_found_hook(s);
2948 if (!s.isWritable())
2953 docstring const file = makeDisplayPath(s.absFilename(), 20);
2954 // Here we probably should run
2955 if (LyXVC::file_not_found_hook(s)) {
2956 docstring const text =
2957 bformat(_("Do you want to retrieve the document"
2958 " %1$s from version control?"), file);
2959 int const ret = Alert::prompt(_("Retrieve from version control?"),
2960 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2963 // How can we know _how_ to do the checkout?
2964 // With the current VC support it has to be,
2965 // a RCS file since CVS do not have special ,v files.
2967 return loadLyXFile(s);
2975 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2977 TeXErrors::Errors::const_iterator cit = terr.begin();
2978 TeXErrors::Errors::const_iterator end = terr.end();
2980 for (; cit != end; ++cit) {
2983 int errorRow = cit->error_in_line;
2984 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2990 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2991 } while (found && id_start == id_end && pos_start == pos_end);
2993 errorList.push_back(ErrorItem(cit->error_desc,
2994 cit->error_text, id_start, pos_start, pos_end));
2999 void Buffer::setBuffersForInsets() const
3001 inset().setBuffer(const_cast<Buffer &>(*this));
3005 void Buffer::updateLabels(UpdateScope scope) const
3007 // Use the master text class also for child documents
3008 Buffer const * const master = masterBuffer();
3009 DocumentClass const & textclass = master->params().documentClass();
3011 // keep the buffers to be children in this set. If the call from the
3012 // master comes back we can see which of them were actually seen (i.e.
3013 // via an InsetInclude). The remaining ones in the set need still be updated.
3014 static std::set<Buffer const *> bufToUpdate;
3015 if (scope == UpdateMaster) {
3016 // If this is a child document start with the master
3017 if (master != this) {
3018 bufToUpdate.insert(this);
3019 master->updateLabels();
3020 // Do this here in case the master has no gui associated with it. Then,
3021 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3025 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3026 if (bufToUpdate.find(this) == bufToUpdate.end())
3030 // start over the counters in the master
3031 textclass.counters().reset();
3034 // update will be done below for this buffer
3035 bufToUpdate.erase(this);
3037 // update all caches
3038 clearReferenceCache();
3041 Buffer & cbuf = const_cast<Buffer &>(*this);
3043 LASSERT(!text().paragraphs().empty(), /**/);
3046 ParIterator parit = cbuf.par_iterator_begin();
3047 updateLabels(parit);
3050 // TocBackend update will be done later.
3053 cbuf.tocBackend().update();
3054 if (scope == UpdateMaster)
3055 cbuf.structureChanged();
3059 static depth_type getDepth(DocIterator const & it)
3061 depth_type depth = 0;
3062 for (size_t i = 0 ; i < it.depth() ; ++i)
3063 if (!it[i].inset().inMathed())
3064 depth += it[i].paragraph().getDepth() + 1;
3065 // remove 1 since the outer inset does not count
3069 static depth_type getItemDepth(ParIterator const & it)
3071 Paragraph const & par = *it;
3072 LabelType const labeltype = par.layout().labeltype;
3074 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3077 // this will hold the lowest depth encountered up to now.
3078 depth_type min_depth = getDepth(it);
3079 ParIterator prev_it = it;
3082 --prev_it.top().pit();
3084 // start of nested inset: go to outer par
3086 if (prev_it.empty()) {
3087 // start of document: nothing to do
3092 // We search for the first paragraph with same label
3093 // that is not more deeply nested.
3094 Paragraph & prev_par = *prev_it;
3095 depth_type const prev_depth = getDepth(prev_it);
3096 if (labeltype == prev_par.layout().labeltype) {
3097 if (prev_depth < min_depth)
3098 return prev_par.itemdepth + 1;
3099 if (prev_depth == min_depth)
3100 return prev_par.itemdepth;
3102 min_depth = min(min_depth, prev_depth);
3103 // small optimization: if we are at depth 0, we won't
3104 // find anything else
3105 if (prev_depth == 0)
3111 static bool needEnumCounterReset(ParIterator const & it)
3113 Paragraph const & par = *it;
3114 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3115 depth_type const cur_depth = par.getDepth();
3116 ParIterator prev_it = it;
3117 while (prev_it.pit()) {
3118 --prev_it.top().pit();
3119 Paragraph const & prev_par = *prev_it;
3120 if (prev_par.getDepth() <= cur_depth)
3121 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3123 // start of nested inset: reset
3128 // set the label of a paragraph. This includes the counters.
3129 static void setLabel(Buffer const & buf, ParIterator & it)
3131 BufferParams const & bp = buf.masterBuffer()->params();
3132 DocumentClass const & textclass = bp.documentClass();
3133 Paragraph & par = it.paragraph();
3134 Layout const & layout = par.layout();
3135 Counters & counters = textclass.counters();
3137 if (par.params().startOfAppendix()) {
3138 // FIXME: only the counter corresponding to toplevel
3139 // sectionning should be reset
3141 counters.appendix(true);
3143 par.params().appendix(counters.appendix());
3145 // Compute the item depth of the paragraph
3146 par.itemdepth = getItemDepth(it);
3148 if (layout.margintype == MARGIN_MANUAL
3149 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3150 if (par.params().labelWidthString().empty())
3151 par.params().labelWidthString(par.translateIfPossible(layout.labelstring(), bp));
3153 par.params().labelWidthString(docstring());
3156 switch(layout.labeltype) {
3158 if (layout.toclevel <= bp.secnumdepth
3159 && (layout.latextype != LATEX_ENVIRONMENT
3160 || isFirstInSequence(it.pit(), it.plist()))) {
3161 counters.step(layout.counter);
3162 par.params().labelString(
3163 par.expandLabel(layout, bp));
3165 par.params().labelString(docstring());
3168 case LABEL_ITEMIZE: {
3169 // At some point of time we should do something more
3170 // clever here, like:
3171 // par.params().labelString(
3172 // bp.user_defined_bullet(par.itemdepth).getText());
3173 // for now, use a simple hardcoded label
3174 docstring itemlabel;
3175 switch (par.itemdepth) {
3177 itemlabel = char_type(0x2022);
3180 itemlabel = char_type(0x2013);
3183 itemlabel = char_type(0x2217);
3186 itemlabel = char_type(0x2219); // or 0x00b7
3189 par.params().labelString(itemlabel);
3193 case LABEL_ENUMERATE: {
3194 // FIXME: Yes I know this is a really, really! bad solution
3196 docstring enumcounter = from_ascii("enum");
3198 switch (par.itemdepth) {
3207 enumcounter += "iv";
3210 // not a valid enumdepth...
3214 // Maybe we have to reset the enumeration counter.
3215 if (needEnumCounterReset(it))
3216 counters.reset(enumcounter);
3218 counters.step(enumcounter);
3222 switch (par.itemdepth) {
3224 format = N_("\\arabic{enumi}.");
3227 format = N_("(\\alph{enumii})");
3230 format = N_("\\roman{enumiii}.");
3233 format = N_("\\Alph{enumiv}.");
3236 // not a valid enumdepth...
3240 par.params().labelString(counters.counterLabel(
3241 par.translateIfPossible(from_ascii(format), bp)));
3246 case LABEL_SENSITIVE: {
3247 string const & type = counters.current_float();
3248 docstring full_label;
3250 full_label = buf.B_("Senseless!!! ");
3252 docstring name = buf.B_(textclass.floats().getType(type).name());
3253 if (counters.hasCounter(from_utf8(type))) {
3254 counters.step(from_utf8(type));
3255 full_label = bformat(from_ascii("%1$s %2$s:"),
3257 counters.theCounter(from_utf8(type)));
3259 full_label = bformat(from_ascii("%1$s #:"), name);
3261 par.params().labelString(full_label);
3265 case LABEL_NO_LABEL:
3266 par.params().labelString(docstring());
3270 case LABEL_TOP_ENVIRONMENT:
3271 case LABEL_CENTERED_TOP_ENVIRONMENT:
3274 par.params().labelString(
3275 par.translateIfPossible(layout.labelstring(), bp));
3281 void Buffer::updateLabels(ParIterator & parit) const
3283 LASSERT(parit.pit() == 0, /**/);
3285 // set the position of the text in the buffer to be able
3286 // to resolve macros in it. This has nothing to do with
3287 // labels, but by putting it here we avoid implementing
3288 // a whole bunch of traversal routines just for this call.
3289 parit.text()->setMacrocontextPosition(parit);
3291 depth_type maxdepth = 0;
3292 pit_type const lastpit = parit.lastpit();
3293 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3294 // reduce depth if necessary
3295 parit->params().depth(min(parit->params().depth(), maxdepth));
3296 maxdepth = parit->getMaxDepthAfter();
3298 // set the counter for this paragraph
3299 setLabel(*this, parit);
3302 InsetList::const_iterator iit = parit->insetList().begin();
3303 InsetList::const_iterator end = parit->insetList().end();
3304 for (; iit != end; ++iit) {
3305 parit.pos() = iit->pos;
3306 iit->inset->updateLabels(parit);
3312 bool Buffer::nextWord(DocIterator & from, DocIterator & to,
3313 docstring & word) const
3315 bool inword = false;
3316 bool ignoreword = false;
3318 // Go backward a bit if needed in order to return the word currently
3319 // pointed by 'from'.
3320 while (from && from.pos() && isLetter(from))
3322 // OK, we start from here.
3324 while (to.depth()) {
3331 lang_code = to.paragraph().getFontSettings(params(),
3332 to.pos()).language()->code();
3334 // Insets like optional hyphens and ligature
3335 // break are part of a word.
3336 if (!to.paragraph().isInset(to.pos())) {
3337 char_type const c = to.paragraph().getChar(to.pos());
3342 } else { // !isLetter(cur)
3343 if (inword && !word.empty() && !ignoreword)
3355 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3356 WordLangTuple & word_lang, docstring_list & suggestions) const
3359 SpellChecker::Result res = SpellChecker::OK;
3360 SpellChecker * speller = theSpellChecker();
3361 suggestions.clear();
3363 while (nextWord(from, to, word)) {
3365 string lang_code = lyxrc.spellchecker_use_alt_lang
3366 ? lyxrc.spellchecker_alt_lang
3367 : from.paragraph().getFontSettings(params(), from.pos()).language()->code();
3368 WordLangTuple wl(word, lang_code);
3369 res = speller->check(wl);
3370 // ... just bail out if the spellchecker reports an error.
3371 if (!speller->error().empty()) {
3372 throw ExceptionMessage(WarningException,
3373 _("The spellchecker has failed."), speller->error());
3375 if (res != SpellChecker::OK && res != SpellChecker::IGNORED_WORD) {
3381 while (!(word = speller->nextMiss()).empty())
3382 suggestions.push_back(word);