]> git.lyx.org Git - lyx.git/blob - src/buffer.C
a03aface32c044eba9dc2424ae90f3976991759b
[lyx.git] / src / buffer.C
1 /**
2  * \file buffer.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "buffer.h"
14
15 #include "author.h"
16 #include "BranchList.h"
17 #include "buffer_funcs.h"
18 #include "bufferlist.h"
19 #include "bufferparams.h"
20 #include "counters.h"
21 #include "Bullet.h"
22 #include "Chktex.h"
23 #include "debug.h"
24 #include "encoding.h"
25 #include "errorlist.h"
26 #include "exporter.h"
27 #include "format.h"
28 #include "funcrequest.h"
29 #include "gettext.h"
30 #include "insetiterator.h"
31 #include "language.h"
32 #include "LaTeX.h"
33 #include "LaTeXFeatures.h"
34 #include "LyXAction.h"
35 #include "lyxlex.h"
36 #include "lyxtext.h"
37 #include "lyxrc.h"
38 #include "lyxvc.h"
39 #include "lyx_main.h"
40 #include "messages.h"
41 #include "output.h"
42 #include "output_docbook.h"
43 #include "output_latex.h"
44 #include "output_linuxdoc.h"
45 #include "paragraph.h"
46 #include "paragraph_funcs.h"
47 #include "ParagraphParameters.h"
48 #include "pariterator.h"
49 #include "sgml.h"
50 #include "texrow.h"
51 #include "undo.h"
52 #include "version.h"
53
54 #include "insets/insetbibitem.h"
55 #include "insets/insetbibtex.h"
56 #include "insets/insetinclude.h"
57 #include "insets/insettext.h"
58
59 #include "mathed/math_macrotemplate.h"
60 #include "mathed/math_macrotable.h"
61 #include "mathed/math_support.h"
62
63 #include "frontends/Alert.h"
64
65 #include "graphics/Previews.h"
66
67 #include "support/lyxalgo.h"
68 #include "support/filetools.h"
69 #include "support/fs_extras.h"
70 #ifdef USE_COMPRESSION
71 # include "support/gzstream.h"
72 #endif
73 #include "support/lyxlib.h"
74 #include "support/os.h"
75 #include "support/path.h"
76 #include "support/textutils.h"
77 #include "support/convert.h"
78
79 #include <boost/bind.hpp>
80 #include <boost/filesystem/operations.hpp>
81
82 #if defined (HAVE_UTIME_H)
83 # include <utime.h>
84 #elif defined (HAVE_SYS_UTIME_H)
85 # include <sys/utime.h>
86 #endif
87
88 #include <iomanip>
89 #include <stack>
90 #include <sstream>
91 #include <fstream>
92
93
94 using lyx::pos_type;
95 using lyx::pit_type;
96
97 using lyx::support::addName;
98 using lyx::support::bformat;
99 using lyx::support::changeExtension;
100 using lyx::support::cmd_ret;
101 using lyx::support::createBufferTmpDir;
102 using lyx::support::destroyDir;
103 using lyx::support::getFormatFromContents;
104 using lyx::support::isDirWriteable;
105 using lyx::support::libFileSearch;
106 using lyx::support::latex_path;
107 using lyx::support::ltrim;
108 using lyx::support::makeAbsPath;
109 using lyx::support::makeDisplayPath;
110 using lyx::support::makeLatexName;
111 using lyx::support::onlyFilename;
112 using lyx::support::onlyPath;
113 using lyx::support::Path;
114 using lyx::support::quoteName;
115 using lyx::support::removeAutosaveFile;
116 using lyx::support::rename;
117 using lyx::support::runCommand;
118 using lyx::support::split;
119 using lyx::support::subst;
120 using lyx::support::tempName;
121 using lyx::support::trim;
122
123 namespace os = lyx::support::os;
124 namespace fs = boost::filesystem;
125
126 using std::endl;
127 using std::for_each;
128 using std::make_pair;
129
130 using std::ifstream;
131 using std::ios;
132 using std::map;
133 using std::ostream;
134 using std::ostringstream;
135 using std::ofstream;
136 using std::pair;
137 using std::stack;
138 using std::vector;
139 using std::string;
140
141
142 // all these externs should eventually be removed.
143 extern BufferList bufferlist;
144
145 namespace {
146
147 int const LYX_FORMAT = 245;
148
149 } // namespace anon
150
151
152 typedef std::map<string, bool> DepClean;
153
154 class Buffer::Impl
155 {
156 public:
157         Impl(Buffer & parent, string const & file, bool readonly);
158
159         limited_stack<Undo> undostack;
160         limited_stack<Undo> redostack;
161         BufferParams params;
162         LyXVC lyxvc;
163         string temppath;
164         TexRow texrow;
165
166         /// need to regenerate .tex?
167         DepClean dep_clean;
168
169         /// is save needed?
170         mutable bool lyx_clean;
171
172         /// is autosave needed?
173         mutable bool bak_clean;
174
175         /// is this a unnamed file (New...)?
176         bool unnamed;
177
178         /// buffer is r/o
179         bool read_only;
180
181         /// name of the file the buffer is associated with.
182         string filename;
183
184         /// The path to the document file.
185         string filepath;
186
187         boost::scoped_ptr<Messages> messages;
188
189         /** Set to true only when the file is fully loaded.
190          *  Used to prevent the premature generation of previews
191          *  and by the citation inset.
192          */
193         bool file_fully_loaded;
194
195         /// our LyXText that should be wrapped in an InsetText
196         InsetText inset;
197
198         ///
199         MacroTable macros;
200 };
201
202
203 Buffer::Impl::Impl(Buffer & parent, string const & file, bool readonly_)
204         : lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
205           filename(file), filepath(onlyPath(file)), file_fully_loaded(false),
206                 inset(params)
207 {
208         inset.setAutoBreakRows(true);
209         lyxvc.buffer(&parent);
210         temppath = createBufferTmpDir();
211         // FIXME: And now do something if temppath == string(), because we
212         // assume from now on that temppath points to a valid temp dir.
213         // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
214 }
215
216
217 Buffer::Buffer(string const & file, bool readonly)
218         : pimpl_(new Impl(*this, file, readonly))
219 {
220         lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
221 }
222
223
224 Buffer::~Buffer()
225 {
226         lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
227         // here the buffer should take care that it is
228         // saved properly, before it goes into the void.
229
230         closing();
231
232         if (!temppath().empty() && !destroyDir(temppath())) {
233                 Alert::warning(_("Could not remove temporary directory"),
234                         bformat(_("Could not remove the temporary directory %1$s"), temppath()));
235         }
236
237         // Remove any previewed LaTeX snippets associated with this buffer.
238         lyx::graphics::Previews::get().removeLoader(*this);
239 }
240
241
242 LyXText & Buffer::text() const
243 {
244         return const_cast<LyXText &>(pimpl_->inset.text_);
245 }
246
247
248 InsetBase & Buffer::inset() const
249 {
250         return const_cast<InsetText &>(pimpl_->inset);
251 }
252
253
254 limited_stack<Undo> & Buffer::undostack()
255 {
256         return pimpl_->undostack;
257 }
258
259
260 limited_stack<Undo> const & Buffer::undostack() const
261 {
262         return pimpl_->undostack;
263 }
264
265
266 limited_stack<Undo> & Buffer::redostack()
267 {
268         return pimpl_->redostack;
269 }
270
271
272 limited_stack<Undo> const & Buffer::redostack() const
273 {
274         return pimpl_->redostack;
275 }
276
277
278 BufferParams & Buffer::params()
279 {
280         return pimpl_->params;
281 }
282
283
284 BufferParams const & Buffer::params() const
285 {
286         return pimpl_->params;
287 }
288
289
290 ParagraphList & Buffer::paragraphs()
291 {
292         return text().paragraphs();
293 }
294
295
296 ParagraphList const & Buffer::paragraphs() const
297 {
298         return text().paragraphs();
299 }
300
301
302 LyXVC & Buffer::lyxvc()
303 {
304         return pimpl_->lyxvc;
305 }
306
307
308 LyXVC const & Buffer::lyxvc() const
309 {
310         return pimpl_->lyxvc;
311 }
312
313
314 string const & Buffer::temppath() const
315 {
316         return pimpl_->temppath;
317 }
318
319
320 TexRow & Buffer::texrow()
321 {
322         return pimpl_->texrow;
323 }
324
325
326 TexRow const & Buffer::texrow() const
327 {
328         return pimpl_->texrow;
329 }
330
331
332 string const Buffer::getLatexName(bool const no_path) const
333 {
334         string const name = changeExtension(makeLatexName(fileName()), ".tex");
335         return no_path ? onlyFilename(name) : name;
336 }
337
338
339 pair<Buffer::LogType, string> const Buffer::getLogName() const
340 {
341         string const filename = getLatexName(false);
342
343         if (filename.empty())
344                 return make_pair(Buffer::latexlog, string());
345
346         string const path = temppath();
347
348         string const fname = addName(path,
349                                      onlyFilename(changeExtension(filename,
350                                                                   ".log")));
351         string const bname =
352                 addName(path, onlyFilename(
353                         changeExtension(filename,
354                                         formats.extension("literate") + ".out")));
355
356         // If no Latex log or Build log is newer, show Build log
357
358         if (fs::exists(bname) &&
359             (!fs::exists(fname) || fs::last_write_time(fname) < fs::last_write_time(bname))) {
360                 lyxerr[Debug::FILES] << "Log name calculated as: " << bname << endl;
361                 return make_pair(Buffer::buildlog, bname);
362         }
363         lyxerr[Debug::FILES] << "Log name calculated as: " << fname << endl;
364         return make_pair(Buffer::latexlog, fname);
365 }
366
367
368 void Buffer::setReadonly(bool const flag)
369 {
370         if (pimpl_->read_only != flag) {
371                 pimpl_->read_only = flag;
372                 readonly(flag);
373         }
374 }
375
376
377 void Buffer::setFileName(string const & newfile)
378 {
379         pimpl_->filename = makeAbsPath(newfile);
380         pimpl_->filepath = onlyPath(pimpl_->filename);
381         setReadonly(fs::is_readonly(pimpl_->filename));
382         updateTitles();
383 }
384
385
386 // We'll remove this later. (Lgb)
387 namespace {
388
389 void unknownClass(string const & unknown)
390 {
391         Alert::warning(_("Unknown document class"),
392                 bformat(_("Using the default document class, because the "
393                         "class %1$s is unknown."), unknown));
394 }
395
396 } // anon
397
398
399 int Buffer::readHeader(LyXLex & lex)
400 {
401         int unknown_tokens = 0;
402         int line = -1;
403         int begin_header_line = -1;
404
405         // Initialize parameters that may be/go lacking in header:
406         params().branchlist().clear();
407         params().preamble.erase();
408         params().options.erase();
409         params().float_placement.erase();
410         params().paperwidth.erase();
411         params().paperheight.erase();
412         params().leftmargin.erase();
413         params().rightmargin.erase();
414         params().topmargin.erase();
415         params().bottommargin.erase();
416         params().headheight.erase();
417         params().headsep.erase();
418         params().footskip.erase();
419
420         while (lex.isOK()) {
421                 lex.next();
422                 string const token = lex.getString();
423
424                 if (token.empty())
425                         continue;
426
427                 if (token == "\\end_header")
428                         break;
429
430                 ++line;
431                 if (token == "\\begin_header") {
432                         begin_header_line = line;
433                         continue;
434                 }
435
436                 lyxerr[Debug::PARSER] << "Handling document header token: `"
437                                       << token << '\'' << endl;
438
439                 string unknown = params().readToken(lex, token);
440                 if (!unknown.empty()) {
441                         if (unknown[0] != '\\' && token == "\\textclass") {
442                                 unknownClass(unknown);
443                         } else {
444                                 ++unknown_tokens;
445                                 string const s = bformat(_("Unknown token: "
446                                                            "%1$s %2$s\n"),
447                                                          token,
448                                                          lex.getString());
449                                 error(ErrorItem(_("Document header error"), s,
450                                                 -1, 0, 0));
451                         }
452                 }
453         }
454         if (begin_header_line) {
455                 string const s = _("\\begin_header is missing");
456                 error(ErrorItem(_("Document header error"), s, -1, 0, 0));
457         }
458         return unknown_tokens;
459 }
460
461
462 // Uwe C. Schroeder
463 // changed to be public and have one parameter
464 // Returns false if "\end_document" is not read (Asger)
465 bool Buffer::readDocument(LyXLex & lex)
466 {
467         lex.next();
468         string const token = lex.getString();
469         if (token != "\\begin_document") {
470                 string const s = _("\\begin_document is missing");
471                 error(ErrorItem(_("Document header error"), s, -1, 0, 0));
472         }
473
474         // we are reading in a brand new document
475         BOOST_ASSERT(paragraphs().empty());
476
477         readHeader(lex);
478         if (!params().getLyXTextClass().load()) {
479                 string theclass = params().getLyXTextClass().name();
480                 Alert::error(_("Can't load document class"), bformat(
481                                      "Using the default document class, because the "
482                                      " class %1$s could not be loaded.", theclass));
483                 params().textclass = 0;
484         }
485
486         bool const res = text().read(*this, lex);
487         for_each(text().paragraphs().begin(),
488                  text().paragraphs().end(),
489                  bind(&Paragraph::setInsetOwner, _1, &inset()));
490         return res;
491 }
492
493
494 // needed to insert the selection
495 void Buffer::insertStringAsLines(ParagraphList & pars,
496         pit_type & pit, pos_type & pos,
497         LyXFont const & fn, string const & str, bool autobreakrows)
498 {
499         LyXFont font = fn;
500
501         // insert the string, don't insert doublespace
502         bool space_inserted = true;
503         for (string::const_iterator cit = str.begin();
504             cit != str.end(); ++cit) {
505                 Paragraph & par = pars[pit];
506                 if (*cit == '\n') {
507                         if (autobreakrows && (!par.empty() || par.allowEmpty())) {
508                                 breakParagraph(params(), pars, pit, pos,
509                                                par.layout()->isEnvironment());
510                                 ++pit;
511                                 pos = 0;
512                                 space_inserted = true;
513                         } else {
514                                 continue;
515                         }
516                         // do not insert consecutive spaces if !free_spacing
517                 } else if ((*cit == ' ' || *cit == '\t') &&
518                            space_inserted && !par.isFreeSpacing()) {
519                         continue;
520                 } else if (*cit == '\t') {
521                         if (!par.isFreeSpacing()) {
522                                 // tabs are like spaces here
523                                 par.insertChar(pos, ' ', font);
524                                 ++pos;
525                                 space_inserted = true;
526                         } else {
527                                 const pos_type n = 8 - pos % 8;
528                                 for (pos_type i = 0; i < n; ++i) {
529                                         par.insertChar(pos, ' ', font);
530                                         ++pos;
531                                 }
532                                 space_inserted = true;
533                         }
534                 } else if (!isPrintable(*cit)) {
535                         // Ignore unprintables
536                         continue;
537                 } else {
538                         // just insert the character
539                         par.insertChar(pos, *cit, font);
540                         ++pos;
541                         space_inserted = (*cit == ' ');
542                 }
543
544         }
545 }
546
547
548 bool Buffer::readFile(string const & filename)
549 {
550         // Check if the file is compressed.
551         string const format = getFormatFromContents(filename);
552         if (format == "gzip" || format == "zip" || format == "compress") {
553                 params().compressed = true;
554         }
555
556         // remove dummy empty par
557         paragraphs().clear();
558         LyXLex lex(0, 0);
559         lex.setFile(filename);
560         bool ret = readFile(lex, filename);
561
562         // After we have read a file, we must ensure that the buffer
563         // language is set and used in the gui.
564         // If you know of a better place to put this, please tell me. (Lgb)
565         updateDocLang(params().language);
566
567         return ret;
568 }
569
570
571 bool Buffer::fully_loaded() const
572 {
573         return pimpl_->file_fully_loaded;
574 }
575
576
577 void Buffer::fully_loaded(bool const value)
578 {
579         pimpl_->file_fully_loaded = value;
580 }
581
582
583 bool Buffer::readFile(LyXLex & lex, string const & filename)
584 {
585         BOOST_ASSERT(!filename.empty());
586
587         if (!lex.isOK()) {
588                 Alert::error(_("Document could not be read"),
589                              bformat(_("%1$s could not be read."), filename));
590                 return false;
591         }
592
593         lex.next();
594         string const token(lex.getString());
595
596         if (!lex.isOK()) {
597                 Alert::error(_("Document could not be read"),
598                              bformat(_("%1$s could not be read."), filename));
599                 return false;
600         }
601
602         // the first token _must_ be...
603         if (token != "\\lyxformat") {
604                 lyxerr << "Token: " << token << endl;
605
606                 Alert::error(_("Document format failure"),
607                              bformat(_("%1$s is not a LyX document."),
608                                        filename));
609                 return false;
610         }
611
612         lex.next();
613         string tmp_format = lex.getString();
614         //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
615         // if present remove ".," from string.
616         string::size_type dot = tmp_format.find_first_of(".,");
617         //lyxerr << "           dot found at " << dot << endl;
618         if (dot != string::npos)
619                         tmp_format.erase(dot, 1);
620         int const file_format = convert<int>(tmp_format);
621         //lyxerr << "format: " << file_format << endl;
622
623         if (file_format != LYX_FORMAT) {
624                 string const tmpfile = tempName();
625                 if (tmpfile.empty()) {
626                         Alert::error(_("Conversion failed"),
627                                      bformat(_("%1$s is from an earlier"
628                                               " version of LyX, but a temporary"
629                                               " file for converting it could"
630                                               " not be created."),
631                                               filename));
632                         return false;
633                 }
634                 string const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
635                 if (lyx2lyx.empty()) {
636                         Alert::error(_("Conversion script not found"),
637                                      bformat(_("%1$s is from an earlier"
638                                                " version of LyX, but the"
639                                                " conversion script lyx2lyx"
640                                                " could not be found."),
641                                                filename));
642                         return false;
643                 }
644                 ostringstream command;
645                 command << "python " << quoteName(lyx2lyx)
646                         << " -t " << convert<string>(LYX_FORMAT)
647                         << " -o " << quoteName(tmpfile) << ' '
648                         << quoteName(filename);
649                 string const command_str = command.str();
650
651                 lyxerr[Debug::INFO] << "Running '"
652                                     << command_str << '\''
653                                     << endl;
654
655                 cmd_ret const ret = runCommand(command_str);
656                 if (ret.first != 0) {
657                         Alert::error(_("Conversion script failed"),
658                                      bformat(_("%1$s is from an earlier version"
659                                               " of LyX, but the lyx2lyx script"
660                                               " failed to convert it."),
661                                               filename));
662                         return false;
663                 } else {
664                         bool const ret = readFile(tmpfile);
665                         // Do stuff with tmpfile name and buffer name here.
666                         return ret;
667                 }
668
669         }
670
671         if (readDocument(lex)) {
672                 Alert::error(_("Document format failure"),
673                              bformat(_("%1$s ended unexpectedly, which means"
674                                        " that it is probably corrupted."),
675                                        filename));
676         }
677
678         //lyxerr << "removing " << MacroTable::localMacros().size()
679         //      << " temporary macro entries" << endl;
680         //MacroTable::localMacros().clear();
681
682         pimpl_->file_fully_loaded = true;
683         return true;
684 }
685
686
687 // Should probably be moved to somewhere else: BufferView? LyXView?
688 bool Buffer::save() const
689 {
690         // We don't need autosaves in the immediate future. (Asger)
691         resetAutosaveTimers();
692
693         // make a backup
694         string s;
695         if (lyxrc.make_backup) {
696                 s = fileName() + '~';
697                 if (!lyxrc.backupdir_path.empty())
698                         s = addName(lyxrc.backupdir_path,
699                                     subst(os::internal_path(s),'/','!'));
700
701                 // It might very well be that this variant is just
702                 // good enough. (Lgb)
703                 // But to use this we need fs::copy_file to actually do a copy,
704                 // even when the target file exists. (Lgb)
705                 if (fs::exists(fileName()) && fs::is_writable(fs::path(fileName()).branch_path())) {
706                   //try {
707                     fs::copy_file(fileName(), s, false);
708                     //}
709                     //catch (fs::filesystem_error const & fe) {
710                     //lyxerr << "LyX was not able to make backup copy. Beware.\n"
711                     //     << fe.what() << endl;
712                     //}
713                 }
714         }
715
716         if (writeFile(fileName())) {
717                 markClean();
718                 removeAutosaveFile(fileName());
719         } else {
720                 // Saving failed, so backup is not backup
721                 if (lyxrc.make_backup)
722                         rename(s, fileName());
723                 return false;
724         }
725         return true;
726 }
727
728
729 bool Buffer::writeFile(string const & fname) const
730 {
731         if (pimpl_->read_only && fname == fileName())
732                 return false;
733
734         bool retval = false;
735
736         if (params().compressed) {
737 #ifdef USE_COMPRESSION
738                 gz::ogzstream ofs(fname.c_str(), ios::out|ios::trunc);
739                 if (!ofs)
740                         return false;
741
742                 retval = do_writeFile(ofs);
743 #else
744                 return false;
745 #endif
746         } else {
747                 ofstream ofs(fname.c_str(), ios::out|ios::trunc);
748                 if (!ofs)
749                         return false;
750
751                 retval = do_writeFile(ofs);
752         }
753
754         return retval;
755 }
756
757
758 bool Buffer::do_writeFile(ostream & ofs) const
759 {
760 #ifdef HAVE_LOCALE
761         // Use the standard "C" locale for file output.
762         ofs.imbue(std::locale::classic());
763 #endif
764
765         // The top of the file should not be written by params().
766
767         // write out a comment in the top of the file
768         ofs << "#LyX " << lyx_version
769             << " created this file. For more info see http://www.lyx.org/\n"
770             << "\\lyxformat " << LYX_FORMAT << "\n"
771             << "\\begin_document\n";
772
773         // now write out the buffer parameters.
774         ofs << "\\begin_header\n";
775         params().writeFile(ofs);
776         ofs << "\\end_header\n";
777
778         // write the text
779         ofs << "\n\\begin_body\n";
780         text().write(*this, ofs);
781         ofs << "\n\\end_body\n";
782
783         // Write marker that shows file is complete
784         ofs << "\\end_document" << endl;
785
786         // Shouldn't really be needed....
787         //ofs.close();
788
789         // how to check if close went ok?
790         // Following is an attempt... (BE 20001011)
791
792         // good() returns false if any error occured, including some
793         //        formatting error.
794         // bad()  returns true if something bad happened in the buffer,
795         //        which should include file system full errors.
796
797         bool status = true;
798         if (!ofs) {
799                 status = false;
800                 lyxerr << "File was not closed properly." << endl;
801         }
802
803         return status;
804 }
805
806
807 void Buffer::makeLaTeXFile(string const & fname,
808                            string const & original_path,
809                            OutputParams const & runparams,
810                            bool output_preamble, bool output_body)
811 {
812         lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
813
814         ofstream ofs;
815         if (!openFileWrite(ofs, fname))
816                 return;
817
818         makeLaTeXFile(ofs, original_path,
819                       runparams, output_preamble, output_body);
820
821         ofs.close();
822         if (ofs.fail())
823                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
824 }
825
826
827 void Buffer::makeLaTeXFile(ostream & os,
828                            string const & original_path,
829                            OutputParams const & runparams_in,
830                            bool const output_preamble, bool const output_body)
831 {
832         OutputParams runparams = runparams_in;
833
834         // validate the buffer.
835         lyxerr[Debug::LATEX] << "  Validating buffer..." << endl;
836         LaTeXFeatures features(*this, params(), runparams);
837         validate(features);
838         lyxerr[Debug::LATEX] << "  Buffer validation done." << endl;
839
840         texrow().reset();
841
842         // The starting paragraph of the coming rows is the
843         // first paragraph of the document. (Asger)
844         texrow().start(paragraphs().begin()->id(), 0);
845
846         if (output_preamble && runparams.nice) {
847                 os << "%% LyX " << lyx_version << " created this file.  "
848                         "For more info, see http://www.lyx.org/.\n"
849                         "%% Do not edit unless you really know what "
850                         "you are doing.\n";
851                 texrow().newline();
852                 texrow().newline();
853         }
854         lyxerr[Debug::INFO] << "lyx document header finished" << endl;
855         // There are a few differences between nice LaTeX and usual files:
856         // usual is \batchmode and has a
857         // special input@path to allow the including of figures
858         // with either \input or \includegraphics (what figinsets do).
859         // input@path is set when the actual parameter
860         // original_path is set. This is done for usual tex-file, but not
861         // for nice-latex-file. (Matthias 250696)
862         // Note that input@path is only needed for something the user does
863         // in the preamble, included .tex files or ERT, files included by
864         // LyX work without it.
865         if (output_preamble) {
866                 if (!runparams.nice) {
867                         // code for usual, NOT nice-latex-file
868                         os << "\\batchmode\n"; // changed
869                         // from \nonstopmode
870                         texrow().newline();
871                 }
872                 if (!original_path.empty()) {
873                         string const inputpath = latex_path(original_path);
874                         os << "\\makeatletter\n"
875                             << "\\def\\input@path{{"
876                             << inputpath << "/}}\n"
877                             << "\\makeatother\n";
878                         texrow().newline();
879                         texrow().newline();
880                         texrow().newline();
881                 }
882
883                 // Write the preamble
884                 runparams.use_babel = params().writeLaTeX(os, features, texrow());
885
886                 if (!output_body)
887                         return;
888
889                 // make the body.
890                 os << "\\begin{document}\n";
891                 texrow().newline();
892         } // output_preamble
893         lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
894
895         if (!lyxrc.language_auto_begin) {
896                 os << subst(lyxrc.language_command_begin, "$$lang",
897                              params().language->babel())
898                     << endl;
899                 texrow().newline();
900         }
901
902         // if we are doing a real file with body, even if this is the
903         // child of some other buffer, let's cut the link here.
904         // This happens for example if only a child document is printed.
905         string save_parentname;
906         if (output_preamble) {
907                 save_parentname = params().parentname;
908                 params().parentname.erase();
909         }
910
911         // the real stuff
912         latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
913
914         // Restore the parenthood if needed
915         if (output_preamble)
916                 params().parentname = save_parentname;
917
918         // add this just in case after all the paragraphs
919         os << endl;
920         texrow().newline();
921
922         if (!lyxrc.language_auto_end) {
923                 os << subst(lyxrc.language_command_end, "$$lang",
924                              params().language->babel())
925                     << endl;
926                 texrow().newline();
927         }
928
929         if (output_preamble) {
930                 os << "\\end{document}\n";
931                 texrow().newline();
932
933                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
934         } else {
935                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
936                                      << endl;
937         }
938
939         // Just to be sure. (Asger)
940         texrow().newline();
941
942         lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
943         lyxerr[Debug::INFO] << "Row count was " << texrow().rows() - 1
944                             << '.' << endl;
945 }
946
947
948 bool Buffer::isLatex() const
949 {
950         return params().getLyXTextClass().outputType() == LATEX;
951 }
952
953
954 bool Buffer::isLinuxDoc() const
955 {
956         return params().getLyXTextClass().outputType() == LINUXDOC;
957 }
958
959
960 bool Buffer::isLiterate() const
961 {
962         return params().getLyXTextClass().outputType() == LITERATE;
963 }
964
965
966 bool Buffer::isDocBook() const
967 {
968         return params().getLyXTextClass().outputType() == DOCBOOK;
969 }
970
971
972 bool Buffer::isSGML() const
973 {
974         LyXTextClass const & tclass = params().getLyXTextClass();
975
976         return tclass.outputType() == LINUXDOC ||
977                tclass.outputType() == DOCBOOK;
978 }
979
980
981 void Buffer::makeLinuxDocFile(string const & fname,
982                               OutputParams const & runparams,
983                               bool const body_only)
984 {
985         ofstream ofs;
986         if (!openFileWrite(ofs, fname))
987                 return;
988
989         LaTeXFeatures features(*this, params(), runparams);
990         validate(features);
991
992         texrow().reset();
993
994         LyXTextClass const & tclass = params().getLyXTextClass();
995
996         string const & top_element = tclass.latexname();
997
998         if (!body_only) {
999                 ofs << tclass.class_header();
1000
1001                 string preamble = params().preamble;
1002                 string const name = runparams.nice ? changeExtension(pimpl_->filename, ".sgml")
1003                          : fname;
1004                 preamble += features.getIncludedFiles(name);
1005                 preamble += features.getLyXSGMLEntities();
1006
1007                 if (!preamble.empty()) {
1008                         ofs << " [ " << preamble << " ]";
1009                 }
1010                 ofs << ">\n\n";
1011
1012                 if (params().options.empty())
1013                         sgml::openTag(ofs, top_element);
1014                 else {
1015                         string top = top_element;
1016                         top += ' ';
1017                         top += params().options;
1018                         sgml::openTag(ofs, top);
1019                 }
1020         }
1021
1022         ofs << "<!-- LyX "  << lyx_version
1023             << " created this file. For more info see http://www.lyx.org/"
1024             << " -->\n";
1025
1026         linuxdocParagraphs(*this, paragraphs(), ofs, runparams);
1027
1028         if (!body_only) {
1029                 ofs << "\n\n";
1030                 sgml::closeTag(ofs, top_element);
1031         }
1032
1033         ofs.close();
1034         if (ofs.fail())
1035                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1036 }
1037
1038
1039 void Buffer::makeDocBookFile(string const & fname,
1040                              OutputParams const & runparams,
1041                              bool const only_body)
1042 {
1043         ofstream ofs;
1044         if (!openFileWrite(ofs, fname))
1045                 return;
1046
1047         LaTeXFeatures features(*this, params(), runparams);
1048         validate(features);
1049
1050         texrow().reset();
1051
1052         LyXTextClass const & tclass = params().getLyXTextClass();
1053         string const & top_element = tclass.latexname();
1054
1055         if (!only_body) {
1056                 if (runparams.flavor == OutputParams::XML)
1057                         ofs << "<?xml version=\"1.0\" encoding=\""
1058                             << params().language->encoding()->name() << "\"?>\n";
1059
1060                 ofs << "<!DOCTYPE " << top_element << " ";
1061
1062                 if (! tclass.class_header().empty()) ofs << tclass.class_header();
1063                 else if (runparams.flavor == OutputParams::XML)
1064                         ofs << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1065                             << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1066                 else
1067                         ofs << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1068
1069                 string preamble = params().preamble;
1070                 if (runparams.flavor != OutputParams::XML ) {
1071                         preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1072                         preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1073                         preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1074                         preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1075                 }
1076
1077                 string const name = runparams.nice ? changeExtension(pimpl_->filename, ".sgml")
1078                          : fname;
1079                 preamble += features.getIncludedFiles(name);
1080                 preamble += features.getLyXSGMLEntities();
1081
1082                 if (!preamble.empty()) {
1083                         ofs << "\n [ " << preamble << " ]";
1084                 }
1085                 ofs << ">\n\n";
1086         }
1087
1088         string top = top_element;
1089         top += " lang=\"";
1090         if (runparams.flavor == OutputParams::XML)
1091                 top += params().language->code();
1092         else
1093                 top += params().language->code().substr(0,2);
1094         top += '"';
1095
1096         if (!params().options.empty()) {
1097                 top += ' ';
1098                 top += params().options;
1099         }
1100
1101         ofs << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1102             << " file was created by LyX " << lyx_version
1103             << "\n  See http://www.lyx.org/ for more information -->\n";
1104
1105         params().getLyXTextClass().counters().reset();
1106
1107         sgml::openTag(ofs, top);
1108         ofs << '\n';
1109         docbookParagraphs(paragraphs(), *this, ofs, runparams);
1110         sgml::closeTag(ofs, top_element);
1111
1112         ofs.close();
1113         if (ofs.fail())
1114                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1115 }
1116
1117
1118 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1119 // Other flags: -wall -v0 -x
1120 int Buffer::runChktex()
1121 {
1122         busy(true);
1123
1124         // get LaTeX-Filename
1125         string const name = getLatexName();
1126         string const path = temppath();
1127         string const org_path = filePath();
1128
1129         Path p(path); // path to LaTeX file
1130         message(_("Running chktex..."));
1131
1132         // Generate the LaTeX file if neccessary
1133         OutputParams runparams;
1134         runparams.flavor = OutputParams::LATEX;
1135         runparams.nice = false;
1136         makeLaTeXFile(name, org_path, runparams);
1137
1138         TeXErrors terr;
1139         Chktex chktex(lyxrc.chktex_command, name, filePath());
1140         int const res = chktex.run(terr); // run chktex
1141
1142         if (res == -1) {
1143                 Alert::error(_("chktex failure"),
1144                              _("Could not run chktex successfully."));
1145         } else if (res > 0) {
1146                 // Insert all errors as errors boxes
1147                 bufferErrors(*this, terr);
1148         }
1149
1150         busy(false);
1151
1152         return res;
1153 }
1154
1155
1156 void Buffer::validate(LaTeXFeatures & features) const
1157 {
1158         LyXTextClass const & tclass = params().getLyXTextClass();
1159
1160         if (features.isAvailable("dvipost") && params().tracking_changes
1161             && params().output_changes)
1162                 features.require("dvipost");
1163
1164         // AMS Style is at document level
1165         if (params().use_amsmath == BufferParams::AMS_ON
1166             || tclass.provides(LyXTextClass::amsmath))
1167                 features.require("amsmath");
1168
1169         for_each(paragraphs().begin(), paragraphs().end(),
1170                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1171
1172         // the bullet shapes are buffer level not paragraph level
1173         // so they are tested here
1174         for (int i = 0; i < 4; ++i) {
1175                 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1176                         int const font = params().user_defined_bullet(i).getFont();
1177                         if (font == 0) {
1178                                 int const c = params()
1179                                         .user_defined_bullet(i)
1180                                         .getCharacter();
1181                                 if (c == 16
1182                                    || c == 17
1183                                    || c == 25
1184                                    || c == 26
1185                                    || c == 31) {
1186                                         features.require("latexsym");
1187                                 }
1188                         } else if (font == 1) {
1189                                 features.require("amssymb");
1190                         } else if ((font >= 2 && font <= 5)) {
1191                                 features.require("pifont");
1192                         }
1193                 }
1194         }
1195
1196         if (lyxerr.debugging(Debug::LATEX)) {
1197                 features.showStruct();
1198         }
1199 }
1200
1201
1202 void Buffer::getLabelList(vector<string> & list) const
1203 {
1204         /// if this is a child document and the parent is already loaded
1205         /// Use the parent's list instead  [ale990407]
1206         Buffer const * tmp = getMasterBuffer();
1207         if (!tmp) {
1208                 lyxerr << "getMasterBuffer() failed!" << endl;
1209                 BOOST_ASSERT(tmp);
1210         }
1211         if (tmp != this) {
1212                 tmp->getLabelList(list);
1213                 return;
1214         }
1215
1216         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1217                 it.nextInset()->getLabelList(*this, list);
1218 }
1219
1220
1221 // This is also a buffer property (ale)
1222 void Buffer::fillWithBibKeys(vector<pair<string, string> > & keys)
1223         const
1224 {
1225         /// if this is a child document and the parent is already loaded
1226         /// use the parent's list instead  [ale990412]
1227         Buffer const * tmp = getMasterBuffer();
1228         BOOST_ASSERT(tmp);
1229         if (tmp != this) {
1230                 tmp->fillWithBibKeys(keys);
1231                 return;
1232         }
1233
1234         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1235                 if (it->lyxCode() == InsetBase::BIBTEX_CODE) {
1236                         InsetBibtex const & inset =
1237                                 dynamic_cast<InsetBibtex const &>(*it);
1238                         inset.fillWithBibKeys(*this, keys);
1239                 } else if (it->lyxCode() == InsetBase::INCLUDE_CODE) {
1240                         InsetInclude const & inset =
1241                                 dynamic_cast<InsetInclude const &>(*it);
1242                         inset.fillWithBibKeys(*this, keys);
1243                 } else if (it->lyxCode() == InsetBase::BIBITEM_CODE) {
1244                         InsetBibitem const & inset =
1245                                 dynamic_cast<InsetBibitem const &>(*it);
1246                         string const key = inset.getContents();
1247                         string const opt = inset.getOptions();
1248                         string const ref; // = pit->asString(this, false);
1249                         string const info = opt + "TheBibliographyRef" + ref;
1250                         keys.push_back(pair<string, string>(key, info));
1251                 }
1252         }
1253 }
1254
1255
1256 bool Buffer::isDepClean(string const & name) const
1257 {
1258         DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1259         if (it == pimpl_->dep_clean.end())
1260                 return true;
1261         return it->second;
1262 }
1263
1264
1265 void Buffer::markDepClean(string const & name)
1266 {
1267         pimpl_->dep_clean[name] = true;
1268 }
1269
1270
1271 bool Buffer::dispatch(string const & command, bool * result)
1272 {
1273         return dispatch(lyxaction.lookupFunc(command), result);
1274 }
1275
1276
1277 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1278 {
1279         bool dispatched = true;
1280
1281         switch (func.action) {
1282                 case LFUN_EXPORT: {
1283                         bool const tmp = Exporter::Export(this, func.argument, false);
1284                         if (result)
1285                                 *result = tmp;
1286                         break;
1287                 }
1288
1289                 default:
1290                         dispatched = false;
1291         }
1292         return dispatched;
1293 }
1294
1295
1296 void Buffer::changeLanguage(Language const * from, Language const * to)
1297 {
1298         BOOST_ASSERT(from);
1299         BOOST_ASSERT(to);
1300
1301         lyxerr << "Changing Language!" << endl;
1302
1303         // Take care of l10n/i18n
1304         updateDocLang(to);
1305
1306         for_each(par_iterator_begin(),
1307                  par_iterator_end(),
1308                  bind(&Paragraph::changeLanguage, _1, params(), from, to));
1309
1310         text().current_font.setLanguage(to);
1311         text().real_current_font.setLanguage(to);
1312 }
1313
1314
1315 void Buffer::updateDocLang(Language const * nlang)
1316 {
1317         BOOST_ASSERT(nlang);
1318
1319         pimpl_->messages.reset(new Messages(nlang->code()));
1320 }
1321
1322
1323 bool Buffer::isMultiLingual() const
1324 {
1325         ParConstIterator end = par_iterator_end();
1326         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1327                 if (it->isMultiLingual(params()))
1328                         return true;
1329
1330         return false;
1331 }
1332
1333
1334 ParIterator Buffer::getParFromID(int const id) const
1335 {
1336         ParConstIterator it = par_iterator_begin();
1337         ParConstIterator const end = par_iterator_end();
1338
1339         if (id < 0) {
1340                 // John says this is called with id == -1 from undo
1341                 lyxerr << "getParFromID(), id: " << id << endl;
1342                 return end;
1343         }
1344
1345         for (; it != end; ++it)
1346                 if (it->id() == id)
1347                         return it;
1348
1349         return end;
1350 }
1351
1352
1353 bool Buffer::hasParWithID(int const id) const
1354 {
1355         ParConstIterator const it = getParFromID(id);
1356         return it != par_iterator_end();
1357 }
1358
1359
1360 ParIterator Buffer::par_iterator_begin()
1361 {
1362         return ::par_iterator_begin(inset());
1363 }
1364
1365
1366 ParIterator Buffer::par_iterator_end()
1367 {
1368         return ::par_iterator_end(inset());
1369 }
1370
1371
1372 ParConstIterator Buffer::par_iterator_begin() const
1373 {
1374         return ::par_const_iterator_begin(inset());
1375 }
1376
1377
1378 ParConstIterator Buffer::par_iterator_end() const
1379 {
1380         return ::par_const_iterator_end(inset());
1381 }
1382
1383
1384 Language const * Buffer::getLanguage() const
1385 {
1386         return params().language;
1387 }
1388
1389
1390 string const Buffer::B_(string const & l10n) const
1391 {
1392         if (pimpl_->messages.get()) {
1393                 return pimpl_->messages->get(l10n);
1394         }
1395
1396         return _(l10n);
1397 }
1398
1399
1400 bool Buffer::isClean() const
1401 {
1402         return pimpl_->lyx_clean;
1403 }
1404
1405
1406 bool Buffer::isBakClean() const
1407 {
1408         return pimpl_->bak_clean;
1409 }
1410
1411
1412 void Buffer::markClean() const
1413 {
1414         if (!pimpl_->lyx_clean) {
1415                 pimpl_->lyx_clean = true;
1416                 updateTitles();
1417         }
1418         // if the .lyx file has been saved, we don't need an
1419         // autosave
1420         pimpl_->bak_clean = true;
1421 }
1422
1423
1424 void Buffer::markBakClean()
1425 {
1426         pimpl_->bak_clean = true;
1427 }
1428
1429
1430 void Buffer::setUnnamed(bool flag)
1431 {
1432         pimpl_->unnamed = flag;
1433 }
1434
1435
1436 bool Buffer::isUnnamed() const
1437 {
1438         return pimpl_->unnamed;
1439 }
1440
1441
1442 #ifdef WITH_WARNINGS
1443 #warning this function should be moved to buffer_pimpl.C
1444 #endif
1445 void Buffer::markDirty()
1446 {
1447         if (pimpl_->lyx_clean) {
1448                 pimpl_->lyx_clean = false;
1449                 updateTitles();
1450         }
1451         pimpl_->bak_clean = false;
1452
1453         DepClean::iterator it = pimpl_->dep_clean.begin();
1454         DepClean::const_iterator const end = pimpl_->dep_clean.end();
1455
1456         for (; it != end; ++it) {
1457                 it->second = false;
1458         }
1459 }
1460
1461
1462 string const & Buffer::fileName() const
1463 {
1464         return pimpl_->filename;
1465 }
1466
1467
1468 string const & Buffer::filePath() const
1469 {
1470         return pimpl_->filepath;
1471 }
1472
1473
1474 bool Buffer::isReadonly() const
1475 {
1476         return pimpl_->read_only;
1477 }
1478
1479
1480 void Buffer::setParentName(string const & name)
1481 {
1482         params().parentname = name;
1483 }
1484
1485
1486 Buffer const * Buffer::getMasterBuffer() const
1487 {
1488         if (!params().parentname.empty()
1489             && bufferlist.exists(params().parentname)) {
1490                 Buffer const * buf = bufferlist.getBuffer(params().parentname);
1491                 if (buf)
1492                         return buf->getMasterBuffer();
1493         }
1494
1495         return this;
1496 }
1497
1498
1499 MacroData const & Buffer::getMacro(std::string const & name) const
1500 {
1501         return pimpl_->macros.get(name);
1502 }
1503
1504
1505 bool Buffer::hasMacro(string const & name) const
1506 {
1507         return pimpl_->macros.has(name);
1508 }
1509
1510
1511 void Buffer::insertMacro(string const & name, MacroData const & data)
1512 {
1513         MacroTable::globalMacros().insert(name, data);
1514         pimpl_->macros.insert(name, data);
1515 }
1516
1517
1518 void Buffer::buildMacros()
1519 {
1520         // Start with global table.
1521         pimpl_->macros = MacroTable::globalMacros();
1522
1523         // Now add our own.
1524         ParagraphList const & pars = text().paragraphs();
1525         for (size_t i = 0, n = pars.size(); i != n; ++i) {
1526                 //lyxerr << "searching main par " << i
1527                 //      << " for macro definitions" << std::endl;
1528                 InsetList const & insets = pars[i].insetlist;
1529                 InsetList::const_iterator it = insets.begin();
1530                 InsetList::const_iterator end = insets.end();
1531                 for ( ; it != end; ++it) {
1532                         //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1533                         if (it->inset->lyxCode() == InsetBase::MATHMACRO_CODE) {
1534                                 MathMacroTemplate const & mac
1535                                         = static_cast<MathMacroTemplate const &>(*it->inset);
1536                                 insertMacro(mac.name(), mac.asMacroData());
1537                         }
1538                 }
1539         }
1540 }
1541
1542
1543 void Buffer::saveCursor(StableDocIterator cur, StableDocIterator anc)
1544 {
1545         cursor_ = cur;
1546         anchor_ = anc;
1547 }
1548
1549
1550 void Buffer::changeRefsIfUnique(string const & from, string const & to)
1551 {
1552         // Check if the label 'from' appears more than once
1553         vector<string> labels;
1554         getLabelList(labels);
1555
1556         if (lyx::count(labels.begin(), labels.end(), from) > 1)
1557                 return;
1558
1559         InsetBase::Code code = InsetBase::REF_CODE;
1560
1561         ParIterator it = par_iterator_begin();
1562         ParIterator end = par_iterator_end();
1563         for ( ; it != end; ++it) {
1564                 bool changed_inset = false;
1565                 for (InsetList::iterator it2 = it->insetlist.begin();
1566                      it2 != it->insetlist.end(); ++it2) {
1567                         if (it2->inset->lyxCode() == code) {
1568                                 InsetCommand * inset = static_cast<InsetCommand *>(it2->inset);
1569                                 if (inset->getContents() == from) {
1570                                         inset->setContents(to);
1571                                         //inset->setButtonLabel();
1572                                         changed_inset = true;
1573                                 }
1574                         }
1575                 }
1576         }
1577 }