Skip to content
This repository was archived by the owner on Sep 3, 2021. It is now read-only.

Commit f928745

Browse files
committed
Added setting for replacing existing file
Split into multiple files
1 parent eaa9fa2 commit f928745

9 files changed

+248
-252
lines changed

package.json

+12
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,17 @@
3737
"onLanguage:tmlanguage"
3838
],
3939
"contributes": {
40+
"configuration": {
41+
"type": "object",
42+
"title": "tmLanguage library configuration",
43+
"properties": {
44+
"tmLanguage.replaceExistingFile": {
45+
"type": "boolean",
46+
"default": true,
47+
"description": "Whether the the conversion should overwrite existing files or create a new one"
48+
}
49+
}
50+
},
4051
"commands": [
4152
{
4253
"command": "extension.convertToJsonTml",
@@ -135,3 +146,4 @@
135146
"vscode": "^1.0.3"
136147
}
137148
}
149+

readme.md

+4-2
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,7 @@
33
This package provides syntax highlighting for the SublimeText JSON/YAML tmlanguage files in VsCode. The syntax highlighting uses
44
tmLanguage files sourced from https://github.com/SublimeText/PackageDev. Coffee script language information is sourced from https://github.com/aponxi/sublime-better-coffeescript/blob/master/CoffeeScript.tmLanguage
55

6-
7-
This package can now convert between JSON/YAML and standard PLIST tmLanguage files.
6+
This package can now convert between JSON/YAML and standard PLIST tmLanguage files.
87

98
The functionality in this extension is inspired by SublimeText PackageDev, and the lack functionality around tmLanguage files, even though
109
it's a recommended format for VSCODE syntax highlighting.
@@ -25,4 +24,7 @@ Included commands are:
2524
- Convert to tmLanguage file - Converts to PLIST from YAML/JSON
2625
- Convert to YAML-tmLanguage file - Converts to YAML from JSON/PLIST
2726

27+
# Settings
28+
tmLanguage.replaceExistingFile - Whether the conversion replaces the existing file or creates a new one. Defaults to true
29+
2830
Please raise any issues with this extension through [GitHub](https://github.com/Togusa09/vscode-tmlanguage/issues)

src/JisonTest.ts

-2
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,6 @@ export class JisonTest{
3131

3232
"tokens": "STRING NUMBER { } [ ] , : TRUE FALSE NULL",
3333
"start": "JSONText",
34-
3534

3635
"bnf": {
3736
"JSONString": [[ "STRING", "$$ = yytext;" ]],
@@ -69,7 +68,6 @@ export class JisonTest{
6968
}
7069
};
7170

72-
7371
main : any = function main () {
7472
var options = {type: "slr", moduleType: "commonjs", moduleName: "jsoncheck"};
7573
var code = new Generator(exports.grammar, options).generate();

src/JsonTmLanguageCompletionItemProvider.ts

+1-5
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,5 @@
11
import * as vscode from 'vscode';
2-
import {join, basename} from 'path';
3-
4-
var plist = require("plist");
5-
var json = require('format-json');
6-
var YAML = require('yamljs');
2+
import { join, basename } from 'path';
73

84
import jsonTmLanguageAnalyser from './jsonTmLanguageAnalyser';
95

src/extension.ts

+2-239
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,11 @@
11
'use strict';
22

33
import * as vscode from 'vscode';
4-
import * as path from 'path';
5-
import * as fs from "fs";
6-
7-
import * as plist from 'plist';
8-
import * as json from 'format-json';
9-
import * as YAML from 'yamljs';
10-
11-
import { Parser } from 'jison';
12-
134
import JsonTmLanguageCompletionItemProvider from './JsonTmLanguageCompletionItemProvider';
145
import jsonTmLanguageDiagnosticProvider from './jsonTmLanguageDiagnosticProvider';
15-
6+
import { FileConverter } from './fileConverter';
167

178
export const JSON_FILE: vscode.DocumentFilter = { language: 'json-tmlanguage', scheme: 'file' };
18-
type SupportedLanguage = "xml" | "tmlanguage" | "json" | "json-tmlanguage" | "yaml" | "yaml-tmlanguage";
199

2010
export function activate(context: vscode.ExtensionContext) {
2111
console.log("Loading tmLanguage extension");
@@ -56,231 +46,4 @@ export function activate(context: vscode.ExtensionContext) {
5646
} catch(err) {
5747
console.log("Failed to load tmLanguage extension due to " + err);
5848
}
59-
}
60-
61-
class FileConverter{
62-
public convertFileToJsonTml() {
63-
return this.ConvertFile( "json-tmlanguage");
64-
}
65-
66-
public convertFileToYamlTml(){
67-
return this.ConvertFile( "yaml-tmlanguage");
68-
}
69-
70-
public convertFileToTml(){
71-
return this.ConvertFile( "tmlanguage");
72-
}
73-
74-
public convertFileToAuto(){
75-
return this.ConvertFile( "yaml-tmlanguage");
76-
}
77-
78-
public dispose(): void {
79-
// nothing to do
80-
}
81-
82-
private fileExtensionFor(destinationLanguage: string): string {
83-
switch (destinationLanguage.toLowerCase()) {
84-
case "json-tmlanguage":
85-
return "JSON-tmLanguage";
86-
case "yaml-tmlanguage":
87-
return "YAML-tmLanguage";
88-
case "tmlanguage":
89-
return "tmLanguage";
90-
default:
91-
return undefined;
92-
}
93-
}
94-
95-
private ConvertFile(destinationLanguage: string){
96-
let editor : vscode.TextEditor = vscode.window.activeTextEditor;
97-
98-
if (!editor){
99-
return;
100-
}
101-
102-
const extension: string = this.fileExtensionFor(destinationLanguage);
103-
104-
let doc : vscode.TextDocument = editor.document;
105-
var parsedFilePath: path.ParsedPath = path.parse(doc.fileName);
106-
107-
if (!extension) {
108-
console.log(`Unable to map destination language (${destinationLanguage}) to file extension`);
109-
vscode.window.showErrorMessage(`Unable to map destination language (${destinationLanguage}) to file extension`);
110-
return;
111-
}
112-
113-
try{
114-
const destLanguage: SupportedLanguage = destinationLanguage as SupportedLanguage;
115-
const doc: vscode.TextDocument = editor.document;
116-
const parsedFilePath: path.ParsedPath = path.parse(doc.fileName);
117-
118-
let documentText: string = doc.getText();
119-
120-
console.log(`Converting to ${extension}`);
121-
122-
// Some of the sublime tmlanguage variant files had comments as hints for auto conversion
123-
if (documentText.startsWith("//")){
124-
var lastLineRange : vscode.Range = doc.lineAt(doc.lineCount - 1).range;
125-
documentText = doc.getText(new vscode.Range(new vscode.Position(1, 0), lastLineRange.end));
126-
}
127-
128-
const sourceLanguage: SupportedLanguage = doc.languageId as SupportedLanguage;
129-
let replaceExistingFile = true;
130-
131-
if(replaceExistingFile){
132-
this.createFileReplacingExisting(parsedFilePath, extension, sourceLanguage, destinationLanguage, documentText);
133-
}else{
134-
this.createFileWithUniqueName(parsedFilePath, extension, sourceLanguage, destinationLanguage, documentText)
135-
}
136-
137-
} catch(err) {
138-
console.log(err);
139-
}
140-
}
141-
142-
private createFileReplacingExisting(parsedFilePath: path.ParsedPath, extension: string, sourceLanguage: string, destinationLanguage: string, documentText: string) : void
143-
{
144-
const newFilePath: string = path.join(parsedFilePath.dir, "./" + parsedFilePath.name + "." + extension);
145-
this.ifExists(newFilePath).then((existed: boolean) => {
146-
this.openEditor(sourceLanguage, destinationLanguage, documentText, newFilePath, existed);
147-
}, (reason: any) => {
148-
reason = reason || "Error writing output file";
149-
console.log("Error writing output", reason);
150-
vscode.window.showErrorMessage(reason.toString());
151-
});
152-
}
153-
154-
private createFileWithUniqueName(parsedFilePath: path.ParsedPath, extension: string, sourceLanguage: string, destinationLanguage: string, documentText: string) : void{
155-
// check to see if file already exists
156-
vscode.workspace.findFiles(parsedFilePath.name + "*." + extension, "ABC")
157-
.then(matchingFiles => {
158-
var paths = matchingFiles.map(p => p.fsPath);
159-
160-
var editorWindows = vscode.window.visibleTextEditors.map(x => x.document.fileName);
161-
paths = paths.concat(editorWindows);
162-
163-
var newFilePath = path.join(parsedFilePath.dir, './' + parsedFilePath.name + '.' + extension);
164-
if (matchingFiles.length != 0){
165-
var counter = 1;
166-
while (paths.indexOf(newFilePath) >= 0){
167-
newFilePath = path.join(parsedFilePath.dir, './' + parsedFilePath.name + '(' + counter +').' + extension);
168-
counter++;
169-
}
170-
}
171-
172-
this.openEditor(sourceLanguage, destinationLanguage, documentText, newFilePath, false);
173-
});;
174-
}
175-
176-
// private ifExists(filePath: string) : Promise<boolean>{
177-
// return new Promise<boolean>((resolve, reject) => {
178-
// try{
179-
// vscode.workspace.findFiles(filePath, "ABC")
180-
// .then((matchingFiles : vscode.Uri[]) => {
181-
// resolve(matchingFiles.length > 0);
182-
// }, (reason: any) => {
183-
// resolve(false)
184-
// });
185-
// }
186-
// catch(err){
187-
// reject(err);
188-
// }
189-
// });
190-
// }
191-
192-
private ifExists(filePath: string): Promise<boolean> {
193-
return new Promise((resolve?: (value: boolean) => void, reject?: (reason: any) => void) => {
194-
try {
195-
fs.exists(filePath, (exists: boolean) => {
196-
resolve(exists);
197-
});
198-
} catch (err) {
199-
reject(err);
200-
}
201-
});
202-
}
203-
204-
private parse(sourceLanguage: SupportedLanguage, documentText: string): any {
205-
switch (sourceLanguage) {
206-
case "xml":
207-
case "tmlanguage":
208-
return plist.parse(documentText);
209-
case "json":
210-
case "json-tmlanguage":
211-
return JSON.parse(documentText);
212-
case "yaml":
213-
case "yaml-tmlanguage":
214-
return YAML.parse(documentText);
215-
default:
216-
return undefined;
217-
}
218-
}
219-
220-
private build(destinationLanguage: SupportedLanguage, parsed: any): string {
221-
switch (destinationLanguage) {
222-
case "xml":
223-
case "tmlanguage":
224-
return plist.build(parsed);
225-
case "json":
226-
case "json-tmlanguage":
227-
return json.plain(parsed);
228-
case "yaml":
229-
case "yaml-tmlanguage":
230-
return YAML.stringify(parsed, 6);
231-
default:
232-
return undefined;
233-
}
234-
}
235-
236-
private uriFor(filePath: string, existing: boolean): vscode.Uri {
237-
if (existing) {
238-
return vscode.Uri.parse("file:///" + filePath);
239-
}
240-
241-
return vscode.Uri.parse("untitled:" + filePath);
242-
}
243-
244-
private openEditor(sourceLanguage: string, destinationLanguage:string, documentText: string, path: string, exists: boolean){
245-
const uri: vscode.Uri = this.uriFor(path, exists);
246-
247-
return vscode.workspace.openTextDocument(uri)
248-
.then((doc: vscode.TextDocument) => {
249-
return vscode.window.showTextDocument(doc)
250-
.then((editor: vscode.TextEditor) => {
251-
return editor.edit((edit: vscode.TextEditorEdit) => {
252-
var parsed: string;
253-
254-
const sourceLanguage: SupportedLanguage = doc.languageId as SupportedLanguage;
255-
parsed = this.parse(sourceLanguage, documentText);
256-
257-
if (!parsed){
258-
// Display a message?
259-
console.log("Could not parse source");
260-
return;
261-
}
262-
const destLanguage: SupportedLanguage = destinationLanguage as SupportedLanguage;
263-
var built = this.build(destLanguage, parsed);
264-
265-
if (exists) {
266-
const was: vscode.Selection = editor.selection;
267-
const lastLineRange: vscode.Range = doc.lineAt(doc.lineCount - 1).range;
268-
const beginning: vscode.Position = new vscode.Position(0, 0);
269-
const end: vscode.Position = new vscode.Position(doc.lineCount - 1, lastLineRange.end.character);
270-
const entire: vscode.Range = new vscode.Range(beginning, end);
271-
edit.replace(entire, built);
272-
editor.selection = was;
273-
} else {
274-
edit.insert(new vscode.Position(0, 0), built);
275-
}
276-
277-
});
278-
});
279-
},
280-
(reason: any) => {
281-
reason = reason || "Error opening editor for output file";
282-
console.log("Error opening editor for file", reason);
283-
vscode.window.showErrorMessage(reason.toString());
284-
});
285-
}
286-
}
49+
}

0 commit comments

Comments
 (0)