nnoremap <silent> <buffer> p :call MarkdownClipboardImage()<cr>
function! MarkdownClipboardImage() abort
" Create `img` directory if it doesn't exist
let relative_img_dir = "images"
let absolute_img_dir = getcwd() . "/" . relative_img_dir
if !isdirectory(absolute_img_dir)
silent call mkdir(absolute_img_dir)
endif
" First find out what filename to use
let index = 1
let base_name = "image"
let file_name = base_name . index . "png"
let relative_file_path = relative_img_dir . "/" . file_name
let file_path = absolute_img_dir . "/" . file_name
while filereadable(file_path)
let index = index + 1
let file_name = base_name . index . ".png"
let relative_file_path = relative_img_dir . "/" . file_name
let file_path = absolute_img_dir . "/" . file_name
endwhile
let clip_command = 'osascript'
let clip_command .= ' -e "set png_data to the clipboard as «class PNGf»"'
let clip_command .= ' -e "set referenceNumber to open for access POSIX path of'
let clip_command .= ' (POSIX file \"' . file_path . '\") with write permission"'
let clip_command .= ' -e "write png_data to referenceNumber"'
silent call system(clip_command)
if v:shell_error == 1
normal! p
else
execute "normal! i[". file_name . "](" . relative_file_path . ")"
endif
endfunction