Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork96
Usage Recipes
Examples of use cases for nvim-notify
These examples assume that you have set nvim-notify as your vim.notify handler
vim.notify=require("notify")
Usesjobstart to run asynchronously.
localfunctionnotify_output(command,opts)localoutput=""localnotificationlocalnotify=function(msg,level)localnotify_opts=vim.tbl_extend("keep",optsor {}, {title=table.concat(command,""),replace=notification } )notification=vim.notify(msg,level,notify_opts)endlocalon_data=function(_,data)output=output..table.concat(data,"\n")notify(output,"info")endvim.fn.jobstart(command, {on_stdout=on_data,on_stderr=on_data,on_exit=function(_,code)if#output==0thennotify("No output of command, exit code:"..code,"warn")endend, })endnotify_output({"echo","hello world"})
Both LSP (Language Server Protocol) and DAP (Debug Adapter Protocol) provide progress notification.The following snippets usenvim-notify to render them.
As a base line, you will need the following functions
-- Utility functions shared between progress reports for LSP and DAPlocalclient_notifs= {}localfunctionget_notif_data(client_id,token)ifnotclient_notifs[client_id]thenclient_notifs[client_id]= {}endifnotclient_notifs[client_id][token]thenclient_notifs[client_id][token]= {}endreturnclient_notifs[client_id][token]endlocalspinner_frames= {"⣾","⣽","⣻","⢿","⡿","⣟","⣯","⣷"}localfunctionupdate_spinner(client_id,token)localnotif_data=get_notif_data(client_id,token)ifnotif_data.spinnerthenlocalnew_spinner= (notif_data.spinner+1)%#spinner_framesnotif_data.spinner=new_spinnernotif_data.notification=vim.notify(nil,nil, {hide_from_history=true,icon=spinner_frames[new_spinner],replace=notif_data.notification, })vim.defer_fn(function()update_spinner(client_id,token)end,100)endendlocalfunctionformat_title(title,client_name)returnclient_name.. (#title>0and":"..titleor"")endlocalfunctionformat_message(message,percentage)return (percentageandpercentage.."%\t"or"").. (messageor"")end
To integrate with progress notifications provided through Neovim's LSP functionality, you can usenvim-lsp-notify plugin, or do-it-yourself:
-- LSP integration-- Make sure to also have the snippet with the common helper functions in your config!vim.lsp.handlers["$/progress"]=function(_,result,ctx)localclient_id=ctx.client_idlocalval=result.valueifnotval.kindthenreturnendlocalnotif_data=get_notif_data(client_id,result.token)ifval.kind=="begin"thenlocalmessage=format_message(val.message,val.percentage)notif_data.notification=vim.notify(message,"info", {title=format_title(val.title,vim.lsp.get_client_by_id(client_id).name),icon=spinner_frames[1],timeout=false,hide_from_history=false, })notif_data.spinner=1update_spinner(client_id,result.token)elseifval.kind=="report"andnotif_datathennotif_data.notification=vim.notify(format_message(val.message,val.percentage),"info", {replace=notif_data.notification,hide_from_history=false, })elseifval.kind=="end"andnotif_datathennotif_data.notification=vim.notify(val.messageandformat_message(val.message)or"Complete","info", {icon="",replace=notif_data.notification,timeout=3000, })notif_data.spinner=nilendend
-- table from lsp severity to vim severity.localseverity= {"error","warn","info","info",-- map both hint and info to info?}vim.lsp.handlers["window/showMessage"]=function(err,method,params,client_id)vim.notify(method.message,severity[params.type])end
To integrate with progress notifications provided bynvim-dap, you can use
-- DAP integration-- Make sure to also have the snippet with the common helper functions in your config!dap.listeners.before['event_progressStart']['progress-notifications']=function(session,body)localnotif_data=get_notif_data("dap",body.progressId)localmessage=format_message(body.message,body.percentage)notif_data.notification=vim.notify(message,"info", {title=format_title(body.title,session.config.type),icon=spinner_frames[1],timeout=false,hide_from_history=false, })notif_data.notification.spinner=1,update_spinner("dap",body.progressId)enddap.listeners.before['event_progressUpdate']['progress-notifications']=function(session,body)localnotif_data=get_notif_data("dap",body.progressId)notif_data.notification=vim.notify(format_message(body.message,body.percentage),"info", {replace=notif_data.notification,hide_from_history=false, })enddap.listeners.before['event_progressEnd']['progress-notifications']=function(session,body)localnotif_data=client_notifs["dap"][body.progressId]notif_data.notification=vim.notify(body.messageandformat_message(body.message)or"Complete","info", {icon="",replace=notif_data.notification,timeout=3000 })notif_data.spinner=nilend

Add the following snippet to yourinit.vim, afternotify extension is loaded andvim.notify is pointing torequire("notify").
lua << EOFlocal coc_status_record= {}functioncoc_status_notify(msg,level) local notify_opts= {title="LSP Status",timeout=500, hide_from_history= true, on_close= reset_coc_status_record }--if coc_status_recordis not {} thenadd itto notify_optstokey called"replace"if coc_status_record ~= {} then notify_opts["replace"]= coc_status_record.idend coc_status_record=vim.notify(msg,level, notify_opts)endfunctionreset_coc_status_record(window) coc_status_record= {}endlocal coc_diag_record= {}functioncoc_diag_notify(msg,level) local notify_opts= {title="LSP Diagnostics",timeout=500, on_close= reset_coc_diag_record }--if coc_diag_recordis not {} thenadd itto notify_optstokey called"replace"if coc_diag_record ~= {} then notify_opts["replace"]= coc_diag_record.idend coc_diag_record=vim.notify(msg,level, notify_opts)endfunctionreset_coc_diag_record(window) coc_diag_record= {}endEOFfunction!s:DiagnosticNotify()abortletl:info=get(b:,'coc_diagnostic_info', {})ifempty(l:info) |return'' |endifletl:msgs= []letl:level='info'ifget(l:info,'warning',0)letl:level='warn'endififget(l:info,'error',0)letl:level='error'endififget(l:info,'error',0)calladd(l:msgs,' Errors:' .l:info['error'])endififget(l:info,'warning',0)calladd(l:msgs,' Warnings:' .l:info['warning'])endififget(l:info,'information',0)calladd(l:msgs,' Infos:' .l:info['information'])endififget(l:info,'hint',0)calladd(l:msgs,' Hints:' .l:info['hint'])endifletl:msg=join(l:msgs,"\n")ifempty(l:msg) |letl:msg=' All OK' |endifcallv:lua.coc_diag_notify(l:msg,l:level)endfunctionfunction!s:StatusNotify()abortletl:status=get(g:,'coc_status','')letl:level='info'ifempty(l:status) |return'' |endifcallv:lua.coc_status_notify(l:status,l:level)endfunctionfunction!s:InitCoc()abortexecute"lua vim.notify('Initialized coc.nvim for LSP support', 'info', { title = 'LSP Status' })"endfunction" notificationsautocmdUserCocNvimInitcalls:InitCoc()autocmdUserCocDiagnosticChangecalls:DiagnosticNotify()autocmdUserCocStatusChangecalls:StatusNotify()

coc.nvim uses echo* commands to write variety of messages. In order to intercept those, monkey patching it by utilizing vim'safter directory (see:help after-directory) is one approach.
First, createcoc/ui.vim file in theautoload after-directory in your vim's runtime path (e.g.~/.vim/after/autoload). For instance, place the following content in the file~/.vim/after/autoload/coc/ui.vim --
scriptencoding utf-8ifhas("nvim")" overwrite coc#ui#echo_messages function to use notifyfunction!coc#ui#echo_messages(hl, msgs)ifa:hl!~#'Error'&& (mode()!~#'\v^(i|n)$')returnendiflet msgs=filter(copy(a:msgs),'!empty(v:val)')ifempty(msgs)returnendif" map a:hl highlight groups to notify levels" if hl matches Error then level is error" if hl matches Warning then level is warn" otherwise level is infoletlevel='info'ifa:hl=~#'Error'letlevel='error'elseifa:hl=~#'Warning'letlevel='warn'endiflet msg=join(msgs,'\n')callv:lua.coc_notify(msg,level)endfunctionfunction!coc#ui#echo_lines(lines)let msg=join(a:lines,"\n")callv:lua.coc_notify(msg,'info')endfunctionendif
Next, manually source this file after coc.nvim has initialized. You can modifys:InitCoc function from the previous example/section and add the functioncoc_notify --
function!s:InitCoc()abort" load overridesruntime! autoload/coc/ui.vimexecute"lua vim.notify('Initialized coc.nvim for LSP support', 'info', { title = 'LSP Status' })"endfunctionfunctioncoc_notify(msg,level) local notify_opts= {title="LSP Message",timeout=500 }vim.notify(msg,level, notify_opts)end