]> git.lyx.org Git - lyx.git/blob - src/Buffer.h
Introducing Font::validate().
[lyx.git] / src / Buffer.h
1 // -*- C++ -*-
2 /**
3  * \file Buffer.h
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author Lars Gullik Bjønnes
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #ifndef BUFFER_H
13 #define BUFFER_H
14
15 #include "insets/InsetCode.h"
16
17 #include "support/FileName.h"
18 #include "support/docstring.h"
19 #include "support/docstream.h"
20 #include "support/types.h"
21
22 #include <iosfwd>
23 #include <string>
24 #include <utility>
25 #include <vector>
26
27
28 namespace lyx {
29
30 class BufferParams;
31 class EmbeddedFiles;
32 class ErrorItem;
33 class ErrorList;
34 class FuncRequest;
35 class Inset;
36 class Font;
37 class Lexer;
38 class LyXRC;
39 class Text;
40 class LyXVC;
41 class LaTeXFeatures;
42 class Language;
43 class MacroData;
44 class OutputParams;
45 class ParConstIterator;
46 class ParIterator;
47 class ParagraphList;
48 class TeXErrors;
49 class TexRow;
50 class TocBackend;
51 class Undo;
52
53 namespace frontend {
54 class GuiBufferDelegate;
55 class WorkAreaManager;
56 }
57
58 /** The buffer object.
59  * This is the buffer object. It contains all the informations about
60  * a document loaded into LyX.
61  * The buffer object owns the Text (wrapped in an InsetText), which
62  * contains the individual paragraphs of the document.
63  *
64  *
65  * I am not sure if the class is complete or
66  * minimal, probably not.
67  * \author Lars Gullik Bjønnes
68  */
69 class Buffer {
70 public:
71         /// What type of log will \c getLogName() return?
72         enum LogType {
73                 latexlog, ///< LaTeX log
74                 buildlog  ///< Literate build log
75         };
76
77         /// Result of \c readFile()
78         enum ReadStatus {
79                 failure, ///< The file could not be read
80                 success, ///< The file could not be read
81                 wrongversion ///< The version of the file does not match ours
82         };
83
84         /// Method to check if a file is externally modified, used by 
85         /// isExternallyModified()
86         /**
87          * timestamp is fast but inaccurate. For example, the granularity
88          * of timestamp on a FAT filesystem is 2 second. Also, various operations
89          * may touch the timestamp of a file even when its content is unchanged.
90          *
91          * checksum is accurate but slow, which can be a problem when it is 
92          * frequently used, or used for a large file on a slow (network) file
93          * system.
94          */
95         enum CheckMethod {
96                 checksum_method,  ///< Use file check sum
97                 timestamp_method, ///< Use timestamp, and checksum if timestamp has changed
98         };
99         
100         /** Constructor
101             \param file
102             \param b  optional \c false by default
103         */
104         explicit Buffer(std::string const & file, bool b = false);
105
106         /// Destructor
107         ~Buffer();
108
109         /** High-level interface to buffer functionality.
110             This function parses a command string and executes it
111         */
112         bool dispatch(std::string const & command, bool * result = 0);
113
114         /// Maybe we know the function already by number...
115         bool dispatch(FuncRequest const & func, bool * result = 0);
116
117         /// Load the autosaved file.
118         void loadAutoSaveFile();
119
120         /// read a new document from a string
121         bool readString(std::string const &);
122         /// load a new file
123         bool readFile(support::FileName const & filename);
124
125         /// read the header, returns number of unknown tokens
126         int readHeader(Lexer & lex);
127
128         /** Reads a file without header.
129             \param par if != 0 insert the file.
130             \return \c false if file is not completely read.
131         */
132         bool readDocument(Lexer &);
133
134         ///
135         void insertStringAsLines(ParagraphList & plist,
136                 pit_type &, pos_type &,
137                 Font const &, docstring const &, bool);
138         ///
139         ParIterator getParFromID(int id) const;
140         /// do we have a paragraph with this id?
141         bool hasParWithID(int id) const;
142
143         ///
144         frontend::WorkAreaManager & workAreaManager() const;
145
146         /** Save file.
147             Takes care of auto-save files and backup file if requested.
148             Returns \c true if the save is successful, \c false otherwise.
149         */
150         bool save() const;
151
152         /// Write document to stream. Returns \c false if unsuccesful.
153         bool write(std::ostream &) const;
154         /// Write file. Returns \c false if unsuccesful.
155         bool writeFile(support::FileName const &) const;
156
157         /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
158         bool makeLaTeXFile(support::FileName const & filename,
159                            std::string const & original_path,
160                            OutputParams const &,
161                            bool output_preamble = true,
162                            bool output_body = true);
163         /** Export the buffer to LaTeX.
164             If \p os is a file stream, and params().inputenc is "auto" or
165             "default", and the buffer contains text in different languages
166             with more than one encoding, then this method will change the
167             encoding associated to \p os. Therefore you must not call this
168             method with a string stream if the output is supposed to go to a
169             file. \code
170             odocfstream ofs;
171             ofs.open("test.tex");
172             writeLaTeXSource(ofs, ...);
173             ofs.close();
174             \endcode is NOT equivalent to \code
175             odocstringstream oss;
176             writeLaTeXSource(oss, ...);
177             odocfstream ofs;
178             ofs.open("test.tex");
179             ofs << oss.str();
180             ofs.close();
181             \endcode
182          */
183         void writeLaTeXSource(odocstream & os,
184                            std::string const & original_path,
185                            OutputParams const &,
186                            bool output_preamble = true,
187                            bool output_body = true);
188         ///
189         void makeDocBookFile(support::FileName const & filename,
190                              OutputParams const & runparams_in,
191                              bool only_body = false);
192         ///
193         void writeDocBookSource(odocstream & os, std::string const & filename,
194                              OutputParams const & runparams_in,
195                              bool only_body = false);
196         /// returns the main language for the buffer (document)
197         Language const * getLanguage() const;
198         /// get l10n translated to the buffers language
199         docstring const B_(std::string const & l10n) const;
200
201         ///
202         int runChktex();
203         /// return true if the main lyx file does not need saving
204         bool isClean() const;
205         ///
206         bool isBakClean() const;
207         ///
208         bool isDepClean(std::string const & name) const;
209
210         /// whether or not disk file has been externally modified
211         bool isExternallyModified(CheckMethod method) const;
212
213         /// save timestamp and checksum of the given file.
214         void saveCheckSum(std::string const & file) const;
215
216         /// mark the main lyx file as not needing saving
217         void markClean() const;
218
219         ///
220         void markBakClean() const;
221
222         ///
223         void markDepClean(std::string const & name);
224
225         ///
226         void setUnnamed(bool flag = true);
227
228         ///
229         bool isUnnamed() const;
230
231         /// Mark this buffer as dirty.
232         void markDirty();
233
234         /// Returns the buffer's filename. It is always an absolute path.
235         std::string const fileName() const;
236
237         /// Returns the the path where the buffer lives.
238         /// It is always an absolute path.
239         std::string const & filePath() const;
240
241         /** A transformed version of the file name, adequate for LaTeX.
242             \param no_path optional if \c true then the path is stripped.
243         */
244         std::string const getLatexName(bool no_path = true) const;
245
246         /// Get thee name and type of the log.
247         std::pair<LogType, std::string> const getLogName() const;
248
249         /// Change name of buffer. Updates "read-only" flag.
250         void setFileName(std::string const & newfile);
251
252         /// Name of the document's parent
253         void setParentName(std::string const &);
254
255         /** Get the document's master (or \c this if this is not a
256             child document)
257          */
258         Buffer const * getMasterBuffer() const;
259         /** Get the document's master (or \c this if this is not a
260             child document)
261          */
262         Buffer * getMasterBuffer();
263
264         /// Is buffer read-only?
265         bool isReadonly() const;
266
267         /// Set buffer read-only flag
268         void setReadonly(bool flag = true);
269
270         /// returns \c true if the buffer contains a LaTeX document
271         bool isLatex() const;
272         /// returns \c true if the buffer contains a DocBook document
273         bool isDocBook() const;
274         /// returns \c true if the buffer contains a Wed document
275         bool isLiterate() const;
276
277         /** Validate a buffer for LaTeX.
278             This validates the buffer, and returns a struct for use by
279             #makeLaTeX# and others. Its main use is to figure out what
280             commands and packages need to be included in the LaTeX file.
281             It (should) also check that the needed constructs are there
282             (i.e. that the \refs points to coresponding \labels). It
283             should perhaps inset "error" insets to help the user correct
284             obvious mistakes.
285         */
286         void validate(LaTeXFeatures &) const;
287
288         /// Update the cache with all bibfiles in use (including bibfiles
289         /// of loaded child documents).
290         void updateBibfilesCache();
291         /// Return the cache with all bibfiles in use (including bibfiles
292         /// of loaded child documents).
293         std::vector<support::FileName> const & getBibfilesCache() const;
294         ///
295         void getLabelList(std::vector<docstring> &) const;
296
297         ///
298         void changeLanguage(Language const * from, Language const * to);
299
300         ///
301         bool isMultiLingual() const;
302
303         ///
304         BufferParams & params();
305         BufferParams const & params() const;
306
307         /** The list of paragraphs.
308             This is a linked list of paragraph, this list holds the
309             whole contents of the document.
310          */
311         ParagraphList & paragraphs();
312         ParagraphList const & paragraphs() const;
313
314         /// LyX version control object.
315         LyXVC & lyxvc();
316         LyXVC const & lyxvc() const;
317
318         /// Where to put temporary files.
319         std::string const & temppath() const;
320
321         /// Used when typesetting to place errorboxes.
322         TexRow & texrow();
323         TexRow const & texrow() const;
324
325         ///
326         ParIterator par_iterator_begin();
327         ///
328         ParConstIterator par_iterator_begin() const;
329         ///
330         ParIterator par_iterator_end();
331         ///
332         ParConstIterator par_iterator_end() const;
333
334         /** \returns true only when the file is fully loaded.
335          *  Used to prevent the premature generation of previews
336          *  and by the citation inset.
337          */
338         bool fully_loaded() const;
339         /// Set by buffer_funcs' newFile.
340         void fully_loaded(bool);
341
342         /// Our main text (inside the top InsetText)
343         Text & text() const;
344
345         /// Our top InsetText!
346         Inset & inset() const;
347
348         //
349         // Macro handling
350         //
351         ///
352         void buildMacros();
353         ///
354         bool hasMacro(docstring const & name) const;
355         ///
356         MacroData const & getMacro(docstring const & name) const;
357         ///
358         void insertMacro(docstring const & name, MacroData const & data);
359
360         /// Replace the inset contents for insets which InsetCode is equal
361         /// to the passed \p inset_code.
362         void changeRefsIfUnique(docstring const & from, docstring const & to,
363                 InsetCode code);
364
365 /// get source code (latex/docbook) for some paragraphs, or all paragraphs
366 /// including preamble
367         void getSourceCode(odocstream & os, pit_type par_begin, pit_type par_end, bool full_source);
368
369         /// errorLists_ accessors.
370         //@{
371         ErrorList const & errorList(std::string const & type) const;
372         ErrorList & errorList(std::string const & type);
373         //@}
374
375         //@{
376         TocBackend & tocBackend();
377         TocBackend const & tocBackend() const;
378         //@}
379         
380         //@{
381         EmbeddedFiles & embeddedFiles();
382         EmbeddedFiles const & embeddedFiles() const;
383         //@}
384
385         Undo & undo();
386        
387         /// This function is called when the buffer is changed.
388         void changed() const;
389         /// This function is called when the buffer structure is changed.
390         void structureChanged() const;
391         /// This function is called when an embedded file is changed
392         void embeddingChanged() const;
393         /// This function is called when some parsing error shows up.
394         void errors(std::string const & err) const;
395         /// This function is called when the buffer busy status change.
396         void busy(bool on) const;
397         /// This function is called when the buffer readonly status change.
398         void readonly(bool on) const;
399         /// Update window titles of all users.
400         void updateTitles() const;
401         /// Reset autosave timers for all users.
402         void resetAutosaveTimers() const;
403         ///
404         void message(docstring const & msg) const;
405
406         void setGuiDelegate(frontend::GuiBufferDelegate * gui);
407
408         ///
409         void autoSave() const;
410         ///
411         bool writeAs(std::string const & newname = std::string());
412         ///
413         bool menuWrite();
414
415 private:
416         /** Inserts a file into a document
417             \return \c false if method fails.
418         */
419         ReadStatus readFile(Lexer &, support::FileName const & filename,
420                             bool fromString = false);
421
422         /// Use the Pimpl idiom to hide the internals.
423         class Impl;
424         /// The pointer never changes although *pimpl_'s contents may.
425         Impl * const pimpl_;
426
427         /// A cache for the bibfiles (including bibfiles of loaded child
428         /// documents), needed for appropriate update of natbib labels.
429         mutable std::vector<support::FileName> bibfilesCache_;
430
431         frontend::GuiBufferDelegate * gui_;
432 };
433
434
435 } // namespace lyx
436
437 #endif