summaryrefslogtreecommitdiff
path: root/support/delig/delig/DeLig.java
blob: 493e7634227fe772ebf15a7eaf568d4fe5d9bcfc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
package delig;

import java.io.*;
import java.util.Hashtable;
import java.util.regex.*;

/**
 * DeLig disables misplaced ligatures in LaTeX documents
 * using a dictionary approach. 
 * 
 * DeLig is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *
 * It may be copied or modified under the terms of the
 * GNU General Public License version 3
 * as published by the Free Software Foundation
 * (http://www.gnu.org/copyleft/gpl.html).
 *
 * This version is intended for German language texts only. 
 * DeLig is partially based on the Perl script rmligs by Björn Jacke,
 * in particular the wordlist data is based on his igerman98 dictionary.
 * 
 * @author Daniel Warner, delig@nospam@daniel-warner.de
 * @version 2008-03-09
 */
public class DeLig {
    private int minLen = 4;

    private boolean prefixAllowed = true;

    private boolean suffixAllowed = true;

    private boolean properSubwordAllowed = true;

    private int tokensCharShift = 256;
    
    private String [][] tokens =
    	{{"\"-", ""}, {"\\-", ""}, {"\"\"", ""},
	 {"{\\\"a}", "ä"}, {"\\\"a", "ä"}, {"\\\"{a}", "ä"}, {"\"a", "ä"},
	 {"{\\\"o}", "ö"}, {"\\\"o", "ö"}, {"\\\"{o}", "ö"}, {"\"o", "ö"},
	 {"{\\\"u}", "ü"}, {"\\\"u", "ü"}, {"\\\"{u}", "ü"}, {"\"u", "ü"},
    	 {"{\\\"A}", "Ä"}, {"\\\"A", "Ä"}, {"\\\"{A}", "Ä"}, {"\"A", "Ä"},
	 {"{\\\"O}", "Ö"}, {"\\\"O", "Ö"}, {"\\\"{O}", "Ö"}, {"\"O", "Ö"},
	 {"{\\\"U}", "Ü"}, {"\\\"U", "Ü"}, {"\\\"{U}", "Ü"}, {"\"U", "Ü"},
	 {"\\ss{}", "ß"}, {"\\ss", "ß"}, {"\"s", "ß"}, {"\"z", "ß"},
    };

    public void process(String[] args) throws DeLigException {
	println("DeLig [Version 0.1]");
	println("Author: Daniel Warner (delig@nospam@daniel-warner.de)");
	println();
	println("\tDeLig disables misplaced ligatures in LaTeX documents");
	println("\tusing a dictionary approach.");
	println();
	println("DeLig is distributed in the hope that it will be useful,");
	println("but WITHOUT ANY WARRANTY; without even the implied warranty of");
	println("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.");
	println();
	println("It may be copied or modified under the terms of the");
	println("GNU General Public License version 3");
	println("as published by the Free Software Foundation");
	println("(http://www.gnu.org/copyleft/gpl.html).");
	println();
	if (args.length != 2) {
	    println("Usage: DeLig inFilename outFilename");
	} else {
	    try {
		// Build ligature hash table

		Hashtable<String, String> hash = new Hashtable<String, String>();
		try {
		    BufferedReader ligatureFile = new BufferedReader(new FileReader("DeLig.list"));
		    String value;

		    while ((value = ligatureFile.readLine()) != null) {
			String key = value.replace("|", "").toLowerCase();
			hash.put(key, value);
		    }
		    ligatureFile.close();
		} catch (IOException e) {
		    String errorMessage = "Error: Could not read ligature file DeLig.list.";
		    throw new DeLigException(errorMessage);
		}

		// Get filenames

		String inFilename = args[0];
		String outFilename = args[1];

		// Open input and output file

		if (!new File(inFilename).exists()) {
		    String errorMessage = "Error: The input file " + inFilename + " does not exist.";
		    throw new DeLigException(errorMessage);
		}

		if (new File(outFilename).exists()) {
		    String errorMessage = "Error: The output file " + outFilename + " already exists.";
		    throw new DeLigException(errorMessage);
		}

		LineNumberReader in = new LineNumberReader(new FileReader(inFilename));
		PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(outFilename)), true);

		// Process input file and write output file

		println("Processing " + inFilename + " and writing output to " + outFilename + " ...");
		println();

		String leadingBackspacesExpr = "[\\\\]*";
		String firstCharExpr = "([A-Za-zäöüÄÖÜ]|(\\{\\\\\"[aouAOU]\\})|(\\\\\"[aouAOU])|(\\\\\"\\{[aouAOU]\\})|(\"[aouAOU]))";
		String subExpr = "([a-zäöüß]|(\\{\\\\\"[aou]\\})|(\\\\\"[aou])|(\\\\\"\\{[aou]\\})|(\"[aou])|(\\\\ss\\{\\})|(\"s)|(\"z)|(\"-)|(\\\\-)|(\"\"))*";
		String ligatureExpr = "f[fil]";
		String trailingSZ = "(\\\\ss)?";
		String regExpr = leadingBackspacesExpr + firstCharExpr + subExpr + ligatureExpr + subExpr + trailingSZ;
		Pattern pattern = Pattern.compile(regExpr);

		int disabledLigatures = 0; // Counts the number of disabled ligatures
		String inLine; // Currently processed line of the input file
		while ((inLine = in.readLine()) != null) {
		    if (inLine.length() == 0) {
			out.println();
			continue;
		    }

		    String outLine = inLine;
		    boolean lineModified = false;

		    Matcher matcher = pattern.matcher(outLine);
		    int regionEnd = outLine.indexOf("%"); // Ignore comments in LaTeX file, if any
		    regionEnd = (regionEnd >= 0 ? regionEnd : outLine.length());
		    matcher.region(0, regionEnd);

		    while (matcher.find()) {
			MatchResult match = matcher.toMatchResult();
			String word = match.group();

			// Determine ligature, if present

			String compareWord = word.replace("\\\\", "").toLowerCase(); // Remove double backslashes (newline)
			String workWord = word.replace("\\\\", "");
			int removedBackslashes = word.length() - compareWord.length(); // Number of removed backslashes		
			for (int i = 0; i < tokens.length; i++) {
			    compareWord = compareWord.replace(tokens[i][0], tokens[i][1]);
			    workWord = workWord.replace(tokens[i][0], ((char) (i + tokensCharShift)) + "");
			}

			if (compareWord.charAt(0) != '\\') // If compareWord starts with a backslash, then it is a command and may not be modified
			{
			    boolean keyFound = hash.containsKey(compareWord);
			    boolean exactMatchFound = keyFound;
			    boolean prefixFound = false;
			    boolean suffixFound = false;
			    boolean properSubwordFound = false;

			    int start = 0;
			    int end = compareWord.length();

			    if (prefixAllowed && !keyFound) {
				start = 0;
				end = compareWord.length();
				while (end >= minLen && !(keyFound = hash.containsKey(compareWord.substring(0, end)))) {
				    end--;
				}
				prefixFound = keyFound;
			    }

			    if (suffixAllowed && !keyFound) {
				start = 0;
				end = compareWord.length();
				while (compareWord.length() - start >= minLen && !(keyFound = hash.containsKey(compareWord.substring(start, compareWord.length())))) {
				    start++;
				}
				suffixFound = keyFound;
			    }

			    if (properSubwordAllowed && !keyFound) {
				for (String key : hash.keySet()) {
				    if (compareWord.contains(key)) {
					start = compareWord.indexOf(key);
					end = start + key.length();
					keyFound = true;
					break;
				    }
				}
				properSubwordFound = keyFound;
			    }

			    if (keyFound) {
				String ligatureWord = hash.get(compareWord.substring(start, end));
				String modifiedWord = "";

				// i: Position in workWord, i - delta: Position in compareWord, ligPos: Position in ligatureWord
				int delta = 0;
				int ligPos = 0;
				int i = 0;
				while (i < workWord.length()) {
				    boolean inLigatureWord = (i - delta >= start && i - delta < end);

				    if (inLigatureWord && ligatureWord.charAt(ligPos) == '|') {
					modifiedWord += "\"|";
					ligPos++;
				    } else {
					int charValue = ((int) workWord.charAt(i) - tokensCharShift);
					if (charValue >= 0 && charValue < tokens.length) {
					    modifiedWord += tokens[charValue][0];
					    delta += (1 - tokens[charValue][1].length());
					    if (inLigatureWord) {
						ligPos += tokens[charValue][1].length();
					    }
					} else {
					    modifiedWord += workWord.charAt(i);
					    if (inLigatureWord) {
						ligPos++;
					    }
					}
					i++;
				    }
				}

				outLine = outLine.substring(0, match.start() + removedBackslashes) + modifiedWord + outLine.substring(match.end(), outLine.length());

				String ligaturePosition = "";
				if (exactMatchFound)
				    ligaturePosition = "exact match";
				else if (prefixFound)
				    ligaturePosition = "prefix";
				else if (suffixFound)
				    ligaturePosition = "suffix";
				else if (properSubwordFound)
				    ligaturePosition = "proper subword";

				println("Disabled ligature [" + ligatureWord + ", " + ligaturePosition + "] in line " + in.getLineNumber() + ": " + word.substring(removedBackslashes) + " => " + modifiedWord);
				disabledLigatures++;
				lineModified = true;

				matcher = pattern.matcher(outLine);
				regionEnd = outLine.indexOf("%"); // Ignore comments in LaTeX file, if any
				regionEnd = (regionEnd >= 0 ? regionEnd : outLine.length());
				matcher.region(0, regionEnd);
			    }
			}
		    }
		    if (lineModified) {
			println();
			println("Modified line " + in.getLineNumber() + ":");
			println("Input  : " + inLine);
			println();
			println("Output : " + outLine);
			println();
		    }
		    out.println(outLine); // Write output line to output file
		}

		// Print statistics

		if (disabledLigatures == 0) {
		    println("No ligatures were disabled.");
		} else if (disabledLigatures == 1) {
		    println("Disabled " + disabledLigatures + " ligature in " + inFilename + ".");
		} else {
		    println("Disabled " + disabledLigatures + " ligatures in " + inFilename + ".");
		}

		// Close input and output file

		in.close();
		out.close();
	    } catch (IOException e) {
		throw new DeLigException(e.getMessage());
	    }
	}
    }

    protected void println() {
	System.out.println();
    }

    protected void println(String output) {
	System.out.println(output);
    }

    protected void print(String output) {
	System.out.print(output);
    }

    public static void main(String[] args) {
	try {
	    new DeLig().process(args);
	} catch (DeLigException e) {
	    System.err.println(e.getMessage());
	}
    }
}