Giter VIP home page Giter VIP logo

vscode-markdown-paste-image's Introduction

Markdown Paste

Smartly paste for Markdown.

Support Mac/Windows/Linux!.

Markdown paste demo

Requirements

  • xclip command be required (Linux)
  • powershell command be required (Win32)
  • pbpaste command be required (Mac)

Features

  • Paste smart

    Smartly paste in Markdown by pressing 'Ctrl+Alt+V' ('Cmd+Alt+V' on Mac) or Markdown Paste command.

    • If you paste an image, the extension will create an new file for the image and insert link code to Markdown.
    • If you paste a text, it will test the text with customize regex, and replace matched content by regex.
    • If you paste a text contain HTML tag, it will try to convert the HTML content to Markdown.
    • If you paste a rich text, it will try to convert the rich text to Markdown.
  • Download file

    Use Markdown Download command (Linux or Windows:Ctrl+Alt+D, Mac:Cmd+Alt+D) to download file and insert link code into Markdown.

  • Paste code

    Use Markdown Paste Code command (Linux or Window:Ctrl+Alt+C, Mac:Cmd+Alt+C) to paste code with auto-detecting language.

  • Ruby tag

    Also, if you want to write article for learning Asia language like Chinese or Japanese, ruby tag(for example:聪明(Cōngmíng)) may be useful. Now a ruby tag snippet are prepare for you, select some text and press 'Ctrl+Alt+T'.

    <ruby>聪明<rp>(</rp><rt>pronunciation</rt><rp>)</rp></ruby>

    This extension will not get the pronunciation for you in this version. You have to replace 'pronunciation' by yourself.

  • Insert latex math symbol and emoji

    You can insert latex math symbol and emoji to any text file, such as Julia source file.

    Press 'Ctrl+Alt+\' or input "Insert latex math symbol" in vscode command panel, then input latex symbol name and choose symbol you want.

  • Embed base64 image

    While you paste image or download image, you can force the extension to insert embed base64 image to markdown by empty filename.

Config

  • Predefined variables

    • ${workspaceRoot} or ${workspaceFolder} - the path of the folder opened in VS Code
    • ${workspaceFolderBasename} - the name of the folder opened in VS Code without any slashes (/)
    • ${fileWorkspaceFolder} - the current opened file's workspace folder
    • ${file} or ${filePath} - the current opened file
    • ${relativeFileDirname} - the current opened file's dirname relative to $fileWorkspaceFolder
    • ${fileBasename} - the current opened file's base name
    • ${fileBasenameNoExtension} - the current opened file's base name with no file extension
    • ${fileExtname} - the current opened file's extension
    • ${fileDirname} - the current opened file's directory name
    • ${datetime} - the current date & time formatted by "yyyyMMDDHHmmss", You can customize the format by format string. exp: ${datetime|yyyy-MM-DD_HH-mm-ss}
    • ${selectedText} - the current selected text. If selected text contain illegal characters \/:*?""<>|\r\n it will return "". You can also set the default text, exp: ${selectedText|default text}, If selected text contain illegal characters or selected text is empty it will return the default text.
  • MarkdownPaste.path

    The folder path that image will be saved. Support absolute path and relative path and predefined variables.

    Default value is ${fileDirname}.

  • MarkdownPaste.nameBase

    The string as the default image file name. Support predefined variables.

    Default value is ${datetime|yyyyMMDDHHmmss}.

  • MarkdownPaste.namePrefix

    The string prepend to the default image file name. Support predefined variables.

    Default value is "".

  • MarkdownPaste.nameSuffix

    The string append to the default image file name. Support predefined variables.

    Default value is "".

  • MarkdownPaste.silence

    Enable/disable showing confirm box while paste image. Set this config option to true, filename confirm box will not be shown while paste image.

    Default value is false.

  • MarkdownPaste.enableImgTag

    Enable/disable using HTML img tag with width and height for pasting image. If this option be enabled, you can input width and height by using <filepath>[?width,height] in filename confirm input box. for example input \abc\filename.png?200,100, then <img src='\abc\filename.png' width='200' height='100' /> will be inserted.

    Default value is true.

  • MarkdownPaste.encodePath

    Encode path link to URL-encode format.

    • encodeURI Encode all characters to URL-encode format.
    • encodeSpaceOnly Encode ' '(space) to '%20' only.
    • none Encode nothing.

    Default value is encodeSpaceOnly

  • MarkdownPaste.rules

    If you want to define your own regex to parse and replace content for pasting text. You can fill the following JSON, and set it to this option.

    [{
        // rule 1
        "regex": "(https?:\/\/.*)", // your javascript style regex
        "options": "ig",            // regex option
        "replace": "[]($1)"         // replace string
    },
    {
        // rule 2
        "regex": "(https?:\/\/.*)", // your javascript style regex
        "options": "ig",            // regex option
        "replace": "[]($1)"         // replace string
    },
    ...
    ]

    The extension will try to test text content by regex defined in this option, if matched it will replace content by using the TypeScript function string.replace().

    Default value is:

    [
      {
        "regex": "^(?:https?://)?(?:(?:(?:www\\.?)?youtube\\.com(?:/(?:(?:watch\\?.*?v=([^&\\s]+).*)|))?))",
        "options": "g",
        "replace": "[![](https://img.youtube.com/vi/$1/0.jpg)](https://www.youtube.com/watch?v=$1)"
      },
      {
        "regex": "^(https?://.*)",
        "options": "ig",
        "replace": "[]($1)"
      }
    ]

    NOTE While pasting image, this option also apply to render image path link.

  • MarkdownPaste.applyAllRules

    If true, it will apply all rules to the same text orderly, instead only the first applicable one.

    Default value is True.

  • MarkdownPaste.enableHtmlConverter

    Enable/disable converting html to markdown.

    Default value is True.

  • MarkdownPaste.enableRulesForHtml

    Enable/disable using rules after converting html to markdown.

    Default value is True.

  • MarkdownPaste.lang_rules

    As MarkdownPaste.rules, you can define rules for other language (for example: asciidoc).

    [
      [
        {
          "asciidoc": [
            {
              "regex": "^(?:https?://)?(?:(?:(?:www\\.?)?youtube\\.com(?:/(?:(?:watch\\?.*?v=([^&\\s]+).*)|))?))",
              "options": "g",
              "replace": "image::https://img.youtube.com/vi/$1/0.jpg[link=\"https://www.youtube.com/watch?v=$1\"]"
            },
            {
              "regex": "^(https?://.*)",
              "options": "ig",
              "replace": "image::$1[linktext,300]"
            },
            {
              "regex": "(.*/media/)(.*)",
              "options": "",
              "replace": "image::$2[linktext,300]"
            }
          ]
        },
        {
          "markdownx": [
            {
              "regex": "^(?:https?://)?(?:(?:(?:www\\.?)?youtube\\.com(?:/(?:(?:watch\\?.*?v=([^&\\s]+).*)|))?))",
              "options": "g",
              "replace": "[![](https://img.youtube.com/vi/$1/0.jpg)](https://www.youtube.com/watch?v=$1)"
            },
            {
              "regex": "^(https?://.*)",
              "options": "ig",
              "replace": "[]($1)"
            }
          ]
        }
      ]
    ]

    NOTE If any language rule been matched, it will not apply MarkdownPaste.rules anymore.

FAQ

  1. Extension not working on Windows, nor on Mac.

    #6

Contributing

See the contribution guidelines for ideas and guidance on how to improve the extension. Thank you!

License

The extension and source are licensed under the MIT license.

vscode-markdown-paste-image's People

Contributors

dylansheffer avatar jeffersonding avatar khusmann avatar krepe90 avatar manuth avatar orangex4 avatar pablolion avatar pearj avatar tanbunko avatar telesoho avatar treert avatar vezaynk avatar ysknkd avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

vscode-markdown-paste-image's Issues

Doesn't work on Mac

Paste command just paste text but not markdown markup on Mac. MacOS version: 12.0

Enable 'invalid' filenames

First, I want to thank you for taking on this wonderful little extension - it's superbly useful and the small changes you've made are really well done.

One issue/request, though - not sure what the criteria for a valid filename are, but it seems to be all lower caps, which seems a bit too strict. I currently have to manually input the name due to this restriction, and it'd be great if it could be optional.

While we're at it, having a default storage instead of prompting for a path each time would also be a nice option to opt-in to, but it's a minor thing.

Once again, thanks!

Feature Request: rename image after paste

I think a useful feature for your extension would be to be able to rename the pasted image by editing in markdown. It will paste in with date/time file name and then be able to rename the image file and link in one go.

Paste multiple images at once, like web clipper

It would be nice to support pasting multiple images at once, similar to web clipper, where one can paste part of a page, containing multiple images and images would be downloaded and saved locally. Looks like right now only links to images are saved.

麻烦看下这几个问题

感谢您开发这么好的插件, 我不知道是我没操纵对, 还是本身没有这个功能, 麻烦看下

  1. win系统下同时复制网页的文字和图片时, 只能粘贴到文字, 图片粘贴不上, 能不能弄个文字和图片可以一起复制的功能
  2. win系统下本地图片可以用这个插件插入吗? 我看您有给一个issue回复说在mac下复制路径可以解决, 我在win下复制路径后粘贴的只是路径本身, 不会显示图片
  3. 图片存储目录设置成中文名时会变成显示一段其它的码, 比如我设置成 "./图片" 时, 最终粘贴显示的是20200602104324

感谢您抽空查看, 谢谢.

Fix encoding problem in non-english language in Windows os

I'm using your extension, which has saved me much time.

Everything is fine before I tried to use it when the Markdown file was in a folder with Chinese letter in its name, which means the imagePath below may contain Chinese letter.

private static saveClipboardImageToFileAndGetPath(imagePath, cb: (imagePath: string) => void)

I traced the execution of your extension and found the Chinese part of imagePath became a mess in the callback function of saveClipboardImageToFileAndGetPath:

image

According to your code, when plplatform === 'win32', it will run the /res/pc.ps1 file with PowerShell.
And in the file pc.ps1, the output is exactly the input, without any modification.

param($imagePath)

......

$imagePath

After some search I found this article, which says

When we pipe output data from PowerShell cmdlets into native applications, the output encoding from PowerShell cmdlets is controlled by the $OutputEncoding variable, which is by default set to ASCII

And that's the problem, Chinese letters(and also letters in many other languages) can't be represented in ASCII encoding, so the data.toString() in following code can't get the correct imagePath.

powershell.stdout.on('data', function (data: Buffer) {
    cb(data.toString().trim());
});

AFAIK there's two way to fix the problem:

  • The first way. Since you don't modify the imagePath in file pc.ps1, the code can be rewritten like this:
powershell.on('exit', function (code, signal) {
    cb(imagePath)
 });
powershell.stdout.on('data', function (data: Buffer) {
    // do nothing
});
  • The second way. Add a line to adjust the encoding of output. This will set the output of pc.ps1 to UTF-8, which can represent many letters in various language.
param($imagePath)

......

[System.Console]::OutputEncoding=[System.Text.Encoding]::GetEncoding(65001)
$imagePath

Thanks for your work!

Does Not Work With Remote-WSL Extension

Hello!
This extension doesn't work out of the box with the Windows Subsystem for Linux extension suite.
I am using VScode 1.48, windows 10, WSL & the Remote - WSL extension.

I believe the issue is that this extension, by default, tries to force you to run it on the wsl-remote side which does not have access to the windows clipboard.

I was able to fix the issue by adding this to settings.json:

"remote.extensionKind": {
        "telesoho.vscode-markdown-paste-image": ["ui"],
    }

This forces the extension to run on the UI/Windows side where it has access to the windows clipboard.

This could be fixed by setting vscode-markdown-paste-image to run on the ui/windows side by default when remote extensions are installed.

In the meantime, the above local fix works for wsl if anyone else is having the same issue.

[EDIT: after experimenting with it a bit more, it doesn't actually work, even with this fix. Changing the settings.json so it runs on the ui side lets you access the clipboard. But it does not actually save the image file that you create.]

Create Folder Automatically

Hi, When I use sublimetext, there is also a similar plugin like markdown-past.
When I press ctrl+alt+V, it will auto save my image such as
./myfilename/myfilename01.png.
I try to do the same thing like this:
./${fileBasenameNoExtension}/ ${fileBasenameNoExtension}"
But here comes an error that path is invalid.
It seems not able to create folder automatically, and I have to create manually.
May I ask if it's possible create folder automatically??

command 'telesoho.MarkdownPaste' not found

image

Previously, it still working fine but not today. In particular, the cmd + alt + v keybinding is not working. while it is registered at default_keybindings.json, see below

image

Version: 1.57.1
Commit: 507ce72a4466fbb27b715c3722558bb15afa9f48
Date: 2021-06-17T13:28:32.912Z
Electron: 12.0.7
Chrome: 89.0.4389.128
Node.js: 14.16.0
V8: 8.9.255.25-electron.0
OS: Darwin x64 20.6.0

Doesn't work on Fedora 35

I've just installed the extension in VS Code. It doesn't seem to work at all on my system. I'm using Fedora 35.

extension not working

i downloaded a Visual Studio Code 1.14.1 and installed this extension, when i paste an image, it shows the path select text box, but when i press the enter key , no picture was pasted in the markdown file, neither any image was found in the file path.

Feature request: allow pasting of images in documents of other languages than markdown (like asciidoc)

I know this extension has 'markdown' in the name, but I got notified that the other main 'Image Pasting' extension for vscode is not being maintained anymore. See: mushanshitiancai/vscode-paste-image#100

I would love to be able to use the regex framework of this extension to cater to 'other language' documents (lie Asciidoc) as well. Maybe it is do-able without making a great fuss.

Something like this in settings:

    "[asciidoc]": {
      "MarkdownPaste.rules": [
        {
          "regex": "^(?:https?://)?(?:(?:(?:www\\.?)?youtube\\.com(?:/(?:(?:watch\\?.*?v=([^&\\s]+).*)|))?))",
          "options": "g",
          "replace": "image::https://img.youtube.com/vi/$1/0.jpg[link=https://www.youtube.com/watch?v=$1]",
        },
        {
          "regex": "^(https?://.*)",
          "options": "ig",
          "replace": "image::$1",
        }
      ] 
    }

files being saved to incorrect location

When pasting a file, if the path is set to F:/foo/img/my_image.png, the image is instead saved to C:/foo/img/my_image.png, and the path is also changed to C:/foo/img/my_image.png.

Bug occurs a windows 10 machine, using a fresh install (as of 2021-07-29) of the extension from marketplace.

  • dialog box for saving the image
    dialog box for saving the image

  • text pasted into markdown by the extension
    text pasted into markdown by the extension

The image does in fact get saved to the given location.

Adding the ability to copy gif

Can you add the ability to copy gif. Now when I copy .gif, it will be save as png.

And How to save a picture with the original filename on the internet?

Spaces in the link are not replaced with %20

When for example ${fileBasenameNoExtension} is used for 'Path' building and file name contains spaces these spaces are placed directly to the link in markdown and as result the link is invalid.

Custom filename format

It would be great to have option to change default filename of image.
Now I have to change it for every image...

arch linux xclip not working

According to xclip's information, there is more than one clipboard, but multiple:

  1. primary

  2. secondary

  3. clipboard

  4. buffer-cut

vscode editor using 1. markdown paste using 3.

So, not working

Paste Path add `./` and File name verification support for Chinese

There are times when you need to paste the path with ./.To change it with ./.
The file name may be in Chinese at some point.It is recommended that you change the regular expression that determines the file name's legitimacy.

if (selectText && !/^[^\\/:\*\?""<>|]{1,120}$/.test(selectText)) {
            vscode.window.showInformationMessage('Your selection is not a valid file name!');
            return;
        }

Error when saving image

I've just installed the vscode markdown paste image plugin. Whenever I try to use it I get an error:

Make folder failed:c:/test/2017-05-21-00-25-39.png

Scrrenshot of the error below:

image

My trouble shoothing steps:

  • I have access to the folder I'm trying to save the image into
  • I've tried saving it to a folder that exists
  • I've tried saving it to a sub-folder that does not exist
  • I've tried saving it to the default folder suggested
  • I've tried using it by pressing ctrl-alt-v
  • I've tried using it by selecting Markdown Paste Image from the command bar (ctrl-p)
  • Version 0.4.1 of the plugin
  • Version 1.12.2 of VS Code

Latest changes broke image pasting on macOS

Since the last update I cannot paste images into markdown anymore on macOS Monterey.
I see the following logs:

[12-26 17:27:01] Cannot found script for darwin
[12-26 17:27:01] getClipboardContentType
[12-26 17:27:01] null

A couple days ago it worked perfectly fine.

command 'telesoho.MarkdownPaste' not found

Dear author,

OS: macOS
Plugin version: 0.13.4
VSCode: 1.58.2

After I installed this plugin and tried, just show the error command 'telesoho.MarkdownPaste' not found.

So I tried to downgrade to 0.13.3, works well.
Tried to upgrade to 0.13.4 again, the same issue happened.

Paste rich text

I'd like to be able to paste rich text content and have it converted to md. Ulysses does this with a 'paste from' command.

My workflow with Ulysses: I copy text from powerpoint containing bold, italic, emphasis, and lists and paste it into Ulysses using the 'paste from' feature. Ulysses converts the rich text to MD. I can then copy the MD formatted text to the clipboard as HTML to be pasted into an SQL document.

Pasting "\" in file paths breaks Github markdown rendering

When pasting an image in, it uses "" backslash characters for the file path. This breaks the HTML rendering of the Markdown text in Github.

Broken:

![](folder\image.png)

Expected:

![](folder/image.png)

By correcting the tool to use forward slashes "/" in the image url it will fix the markdown to be compatible with Github.

A little more information about this bug:
The reason paths can be broken if a backslash "" is used is because certain web servers (like Github) are very strict with slashes. All URL paths need to use forward slashes "/" on Github and other server; primarily Linux servers. Windows servers are generally friendly to using either type of slash.

Paste as base64 instead of local file link

I'd like to ask for the mentioned feature, it'll be really great to embed the image in the markdown file!

we can do

... contents
![My Image][my_img]
...contents

[my_img]: data:image/png;base64,blahblahblahblah

By attaching the base64 on the end of file instead of inline it, it won't be ugly but still embed in file.

I really hopy this feature is supported, thank you.

How to paste a local image file?

I try to copy&paste a local image file and hope the link code would point to the existed local file, but it still asked me to create a new file.

"Insert extra newline when calling pasteCode" and potential fix

Hi,

Thanks for the great vscode extension!

I find a strange issue in Window 10 vscode.
I copied 2 lines of python code from VSCode

        screen_width = self.winfo_screenwidth()
        screen_height = self.winfo_screenheight()

After calling "Markdown Paste Code", it automatically insert one additional newline between each line of code.

        screen_width = self.winfo_screenwidth()

        screen_height = self.winfo_screenheight()

I debug the pasteCode() and if I print the content returned by var content = clipboard.readSync(); with console.log(JSON.stringify(content)), the result is

" screen_width = self.winfo_screenwidth()\r\r\n screen_height = self.winfo_screenheight()"

I installed latest "clipboardy" and run following code in node.js, the result is correct

> const clipboard = await import("clipboardy")
> clipboard.default.readSync()
'        screen_width = self.winfo_screenwidth()\r\n' +
  '        screen_height = self.winfo_screenheight()'

So I guess this is a bug of old clipboardy.

I am not able to fix the bug because master branch doesn't contain Markdown Paste Code.
May I know if you can check in the latest code? I can help to fix the bug.

Thanks,
anselmwang

Can't save the images to a default absolute path

I want all the pasted images to go into "C:\Users\KWUIUN\Pictures\Img-repo" without any prompt.

I changed the settings on vscode and added this:

    "MarkdownPaste.path": "C:/Users/KWUIUN/Pictures/Img-repo/",
    "MarkdownPaste.silence": true,

But still asks for the filename of the picture and points to the current relative path of the working space.

How can i do this?

Variable "${workspaceRoot}" looks resolved incorrectly

Dear author,

OS: macOS
Plugin version: 0.13.7
VSCode: 1.58.2

When set Path to "${workspaceRoot}/ABC", the actual path is not the workspace root, but still the same level folder with "[object Object]/ABC/"

Please help to take a look

Provide an option to paste raw text.

Since I want to totally replace the default paste command, I removed all rules, but it still try to convert it.

One case is when I copy & paste multiple lines, it will wrap the text.

Another case is copying url from chrome, it will convert to <some url>.

I hope it can provide an option to disable these features.

Thanks!

Image overriding

I understand why is it so, but...
It can easily happen that I override existing image unintentionally - so my markdown file will be broken on some place... And it does not notify me about overriding ):

(btw - great extension, thanks for it...)

Not working

I am using win 7, VSCode 1.23.1 zip. I've read #6, I've added powershell to my PATH.

When I copy a image file in my explorer, then press Ctrl + Alt + V in a .md file in VSCode, nothing happens. If I Ctrl + Shift + P, choose markdown paste, Code says There is not a image in clipboard.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.