windowspascalfreepascal

How to print emojis using Pascal on Windows cmd/powershell


According to this table the UTF8 code for the smiley emoji is: F0 9F 98 81.

I attempt to write this output to the console, to no avail:

Program emojii;

{$apptype CONSOLE}

Begin
  WriteLn(#$F0#$9F#$98#$81);
End.

The response I get is jargon: 😁

I'm using Windows Terminal Powershell that supports emojiis, as can be seen in the image below:

Windows Terminal Powershell with emojii support

I'm using FreePascal: Free Pascal Compiler version 3.2.2 [2024/02/26] for x86_64. I build with the following command:

fpc emojii.pas

Solution

  • By default Windows CMD and Powershell use code page 437, which doesn't support emojis.

    The solution is to use SetConsoleOutputCP(CP_UTF8) to change the consoles code page to UTF8.

    I've included an example below using both UTF8 and UTF16 codepoints.

    Program Emoji;
    
    {$APPTYPE CONSOLE}
    
    uses
      Windows;
      
    Var
      U8Emoji: String;
      U16Emoji: WideString;
      Converted: String;
    Begin
      // 😁 emoji UTF8 and UTF16 codepoints
      U8Emoji := Char($F0) + Char($9F) + Char($98) + Char($81);
      U16Emoji := WideChar($D83D) + WideChar($DE01);
      
      // Convert UTF16 to UTF8
      Converted := UTF8Encode(U16Emoji);
    
      // Set the Windows console codepage to UTF8. By default CMD and Powershell
      // use code page 437: https://en.wikipedia.org/wiki/Code_page_437
      SetConsoleOutputCP(CP_UTF8);  
    
      // Prints 😁 emoji 
      WriteLn(U8Emoji);
      WriteLn(Converted);
    End.
    

    You will need a font that supports emojis. Windows 11 uses the Segoe UI Emoji font by default.