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