1
+ 'use strict' ;
2
+
3
+ import * as vscode from 'vscode' ;
4
+ import { isString } from 'util' ;
5
+
6
+ export function runMarkdownSnippet ( ) {
7
+ let editor = vscode . window . activeTextEditor ;
8
+ let selection = editor !== undefined ? editor . selection : undefined ;
9
+ if ( editor === undefined || selection === undefined ) {
10
+ vscode . window . showInformationMessage ( 'No code selected.' ) ;
11
+ return ;
12
+ }
13
+
14
+ let snippet = editor . document . getText ( selection ) ;
15
+ let content = Content . parseSnippet ( snippet ) ;
16
+ if ( isString ( content ) ) {
17
+ let error = content ;
18
+ vscode . window . showInformationMessage ( error ) ;
19
+ return ;
20
+ }
21
+ console . log ( content ) ;
22
+
23
+ let uri = editor . document . uri ;
24
+ if ( uri === undefined || uri . scheme !== 'file' ) {
25
+ vscode . window . showInformationMessage ( 'Opened file is not placed at the local filesystem.' ) ;
26
+ return ;
27
+ }
28
+ let config = vscode . workspace . getConfiguration ( "markdown-run-snippet" ) ;
29
+
30
+ // generate temporary file path
31
+ let extension = content . filetype ; // do something to get extension from filetype.
32
+ let tmppath = gentmppath ( uri , extension ) ;
33
+ // vscode.commands.executeCommand('code-runner.run', tmppath);
34
+ }
35
+
36
+ class Content {
37
+ public filetype : string ;
38
+ public content : string ;
39
+
40
+ constructor ( filetype : string , content : string ) {
41
+ this . filetype = filetype ;
42
+ this . content = content ;
43
+ }
44
+
45
+ static parseSnippet ( orig_snippet : string ) : Content | string {
46
+ // unimplemented!
47
+ let snippet = orig_snippet . trim ( ) ;
48
+ if ( ! snippet . startsWith ( '```' ) || ! snippet . endsWith ( '```' ) ) {
49
+ return "Selection is not started with ``` or is not ended with ```" ;
50
+ }
51
+
52
+ snippet = snippet . replace ( / ^ ` ` ` / , '' ) . replace ( / ` ` ` $ / , '' ) ;
53
+
54
+ let splitted_snippet = snippet . split ( '\n' ) ;
55
+ if ( splitted_snippet . length == 0 ) {
56
+ return 'No string inside ```s.' ;
57
+ }
58
+
59
+ let filetype = splitted_snippet [ 0 ] ;
60
+ if ( filetype === "" ) {
61
+ return "No filetype detected." ;
62
+ }
63
+ let content = splitted_snippet . slice ( 1 ) . join ( '\n' ) ;
64
+
65
+ return new Content ( filetype , content ) ;
66
+ }
67
+ }
68
+
69
+ function gentmppath ( uri : vscode . Uri , ext : string ) : string {
70
+ let fsPath = uri . fsPath ;
71
+ return ( dirname ( fsPath ) + '/' + genrndname ( ) + "." + ext ) ;
72
+ }
73
+
74
+ function dirname ( path : string ) : string {
75
+ return path . replace ( / \\ / g, '/' ) . replace ( / \/ [ ^ \/ ] * $ / , '' ) ;
76
+ }
77
+
78
+ function genrndname ( ) : string {
79
+ return 'junk_' + Math . random ( ) . toString ( 36 ) . replace ( / [ ^ a - z ] + / g, '' ) . substr ( 0 , 10 ) ;
80
+ }
0 commit comments